Some util C# snippets of code

Fancy a few handy code snippets for your .NET/Unity project? 😉

This article is also available on Medium.

In lots of my projects, I reuse some basic utilities over and over again: picking an item from a collection at random, initializing an array with all the ints up to a given number, shuffling a list…

So I’ve prepared a little list of handy snippets that I can quickly copy and paste as I work. I thought I’d share it so others can benefit from them!

Quick data manipulation

Snippet #1: Creating an array of integers from 0 to N

Oftentimes, I’m looking for ways to make my arrays initialization phase easier. Because if you don’t want for an array filled with zeros to start with but instead you want some specific values, most of the time you’ll be forced to iterate the array and do the initialization yourself.

A special case though is if you want your array to count up to a given integer N; here, you can make use of the Enumerable type:

Here, you have an additional parameter (the inclusive bool) to choose whether to go from 0 to N or from 0 to only N – 1.

Snippet #2: Displaying a data list as a table

Showing data rows as a pretty-looking table is always great: it can be used for debugging or even as a final output for console applications. But it’s always a pain to re-write all your Console.WriteLine() over and over again! So this function will use a list of headers for the table top-row and then print all of your rows below:

Here’s an example of a result:

Clearly, this function is not “optimized” for complex displays – it doesn’t handle long values with short headers, or multi-typed rows… But it’s still a nice way to get started 🙂

About randomness

Snippet #3: Picking a random item in a collection

It’s quite common for me to work on procedurally generated content and, as such, I definitely need to get random data. Among other things, it’s often interesting to choose some item at random in arrays or lists. This can be done pretty easily by getting a random index in your collection and returning the item at that index:

By the way: this function can work for any collection, any C# IEnumerable 🙂

Snippet #4: Shuffling a collection

Another useful method I keep on reusing is a shuffling function, so that I can rearrange the elements of an array or a list for example in a random order. Here you have a generic function that can take in any collection:

Be careful – when you use this method, you’ll need to cast the result to your actual collection type (because IEnumerable<int> is not the actual type of your variable, your variable is an int[]):

Also, note that this function creates a new list and doesn’t modify the input one (so, here, the a variable still contains the numbers [1, 2, 3, 4] in the right order).

Snippet #5: Getting random non-redundant items in a collection

Our previous snippets can actually be used as a building block of another interesting utility: a random sampling with no repetitions.

Suppose you have some map for a video game you’re designing, with random spawning points. You have S = 8 spawning points, and P = 3 players to spawn when the game first begins. Your first instinct might be to make a little loop and, for each of the 3 players, pick a spawning point at random. But! Doing that has an issue: you could be spawning 2 or even 3 players in the same spot!

To avoid this, a nice technique is to rather make a list of S indices (one for each spawning point), then shuffle it and take only the P first values:

This way, you’re sure to get each spawning point index one and only one time — meaning that you’re sure you won’t be instantiating two characters in the same place 😉

Note: similarly to snippet #4, make sure to cast the result using Linq‘s ToList() or ToArray() for example.

Snippet #6: Using probability vectors

If you’ve ever worked on procedural world generation, you might have had to make biomes; and then, you may have had tiles that you wanted to assign various types to, depending on which biome they were in; and you wanted this type to be chosen at random… but still under some constraints.

Let’s take an example to better understand – say I have a grid of 10×10 tiles that make my ground. And I’ve determined that I want this chunk of map to be a “desert”. In my tile types list, I have 3 “desert types”: sand, rocks and dirt. What I want is for most of the desert to be filled with sand, then some tiles should be dirt and even fewer should be rocks. Rather than using those vague words, let’s say that:

  • 70% of the chunk should be sand
  • 20% should be dirt
  • the remaining 10% will be rocks

This means that when you choose your tile types at random, you’ll actually want to use a specific mathematical distribution that makes the sand more probable than the rocks. This is done by using a probability vector, i.e. by defining a list of floats that all sum up to 1 and represent the “weight” of each part of the [0, 1] range. You basically need to set thresholds (here: 0.7, 0.7 + 0.2 = 0.9 and 0.9 + 0.1 = 1) and checking your random number against those.

This function asks you for a dict that matches each threshold to its item value (in our case: “sand”, “dirt” or “rock”) and the random value that you picked:

This will give you results where you have approximatively (because it’s still random) 60% of “sand” tiles, 30% of “dirt” tiles and the rest of “rock” tiles (here represented by the characters .D and R respectively):

Note: this tool was inspired by the Python numpy‘s package, and specifically its numpy.random.choice method, that can take in a 1D vector of probabilities to apply them to the sampling (instead of the default uniform distribution).

Upgrading your classes

Snippets #7 and #8: Overloading some operators

Just like in C++, C# lets you do some operator overloading. You can use it on your structs and your classes – for example, the following defines how addition works for my custom struct MyStruct (and also how it should be printed in the console):

When it is called, it gives the expected result:

For a more comprehensive example of operator overloading, check out the Microsoft docs 😉

Also, sometimes, your class or your struct is just some big array. What I mean by that is that the class has one field which is an array of some type, and that whenever you interact with instances of this class you’re just accessing this array. In this case, it can be nice to overload the indexing operator:

This can be used as follows:

This technique can also help with data protection — by defining your own accessor, you can restrict the outsiders usage of this class and, for example, make the indexing a getter-only (by simply removing the set {...} part in the above snippet).

Bonus question: Should you use a class or a struct?

As explained in the docs, even though C# structs and classes are pretty similar from a programmer’s standpoint, there actually optimized for different situations.

Structs are value types – this means that they are allocated on the stack, which generally makes for cheaper allocations and deallocations. On the other hand, classes are reference types: they are allocated on the heap and garbage-collected. It’s also why when iterating a collection of items, it will be faster with structs than with classes – since they are value types, they are better “organized” in memory and have a better locality of reference.

But because they are value types, structs are bad whenever you do boxing and unboxing (i.e. you go to and from the C# lazy object type). And if you have a large amount of data that you keep on copying everywhere, references are going to be way better optimized, so you should use classes for that. Plus passing a struct to a function will pass it by value, so it will create an actual copy implicitly, making it impossible to directly affect the original object.

Overall, you should use:

  • structs for small data chunks that don’t live for too long, that aren’t passed around everywhere in your code, that are immutable and that you don’t box and unbox too frequently
  • classes the rest of the time!

Conclusion

I hope those little functions and info can be useful to some — I know I just sprinkle those everywhere in my Unity game projects!

What about you: do you have nice C# util functions or classes you’d like to talk about? If so, feel free to write a comment! 😉

Leave a Reply

Your email address will not be published.