Press "Enter" to skip to content

Category: C# Tips and Techniques

Replace “switch” statements with dictionaries

Long functions can make code difficult to read. We have to use mental energy to remember what was done in the code above the line we’re looking at. Replacing long “switch” statements with a dictionary may make your code shorter and easier to work with. In the sample code, we’re going to handle keyboard input (the WASD keys) changing the location of something on the screen. We’ll use this simple Location class with XPosition and YPosition properties. With the switch statement version of the code, in the window’s constructor, we initialize a Location object and store it to a class-level…

Leave a Comment

Make your code easier to read with “early exits”

One technique to make your code easier to read, and work with, is to use “early exits” in your functions. Here is how I used early exits to clean up a function I wrote for a game. Let’s say we have an online game and want the players to be able to change their character’s name. Here’s the code for our simple Player class, with an Id and Name property. The function to rename the character needs to do several checks to prevent the user from renaming to a bad name, for example: an empty string, a name that another…

Leave a Comment

How to create classes from JSON data files in C#

If you have a JSON data file and would like to quickly build classes you can deserialize the data into, Visual Studio has a simple way for you to do this – without manually creating the properties. Let’s say we want to build a class to hold the data in this config.json file: Create a new class. In this example, I’ll name the class ConfigValues.cs. Delete everything from the file, except for the namespace declaration. Highlight all the data in the JSON file and copy it to the clipboard (Ctrl-C). Go back into the empty class file (ConfigValues.cs) and put…

Leave a Comment

How to get the folder from a file name in C#

To get the directory of a file name in C#, instantiate a FileInfo object, passing in the file name string to the constructor. Then read the DirectoryName property of the FileInfo object. You can get the root drive from the FileInfo.Directory.Root.FullName property. This also works on paths with forward slashes, like Linux systems use. Results, from running the code:

Leave a Comment

How to delete files in C#

To delete a single file in C#, use File.Delete, and pass in a string of the name of the file. Delete a single file If you have the name of a file in a string, you can either call File.Delete (from the System.IO namespace) and pass in the string name, or you can create a FileInfo object (using the string) and call Delete on the FileInfo object. NOTE: This does not allow wildcards in the file name. Delete multiple files (with wildcard) If you want to delete multiple files, using a wildcard, you can create a DirectoryInfo object for the…

Leave a Comment

How to remove spaces from a string in C#

To remove spaces from a string with C#, use the Replace function, passing in the value you want to remove and the value you want to replace it with. To remove characters, make the second parameter an empty string. You can replace a single character or a sequence of characters. Here’s code to demonstrate the Replace function on a string variable. Notice on line 6 that calling the Replace on the string does not change the string. You need to use the technique on line 9 where we put the modified value back into the “test” variable. Here are the…

Leave a Comment

How to convert a string to an enum in C#

To convert a string value to an enum value, use the Enum.TryParse function. This is the enum we’ll use in the example code: Notice that the Completed value for the enum has an “= 42” after it. Enums are like zero-based arrays. By default, the first enum option is number 0, the second is number 1, and so on. However, you can assign specific values to the options. In the code below, we have a list of strings we’ll try to convert to their Status enum value. On line 6, we use Enum.TryParse to attempt to convert the “statusAsString” value…

Leave a Comment

How to get a random number in C#

To generate a random number in C#, either use Random.Next in the System namespace, or the RandomNumberGenerator.GetInt32 function in the System.Security.Cryptography namespace. In the first version, we instantiate a Random object (from the System namespace) on line 1 and use it on line 7 to get a random number from 1 to 10. Notice that the second parameter is 11, not 10. This maxValue parameter needs to be one number higher than the highest number you want the function to return. So, if you want a random number from 1 to 6 (like rolling dice), you need to use 1…

Leave a Comment

How to create extension methods in C#

Extension methods are a way to have a function that can be used by all objects of a specific datatype or interface. They “extend” the functionality of object, without needing to alter the class. Creating extension methods On lines 1-13, we have the class that holds our extension methods. Extension methods must be in a static class. The class is named MyExtensionMethods, but it can be any name. The extension methods are the ToLeetCode function that starts line 3 and the None function that starts on line 9. Both these functions are static – another requirement for extension methods. For…

Leave a Comment

How to set a default value for a property in C#

Here’s how to set default property values for properties in C# On line 3, we have an auto-property “Name”. To set its default value, after the “{ get; set; }” add an equal sign, the value you want for the default, and a semi-colon. On line 6, we have the “PreferredLanguage” property, which uses a backing variable to hold the property’s value. For properties with backing variables, you generally set the backing variable to the default value, like we do on line 5 here. On line 12, we have the “KnownLanguages” property, whose datatype is List<string>. Just like with the…

Leave a Comment