Sunday, October 4, 2015

C# Coder? Make Your Life A Bit Easier With These Code Snips!

Awesome little C# tricks

C# is a very powerful flexible programming language and the .NET standard library offer tons of great functionality ready to use in your code. As a developer, I always look for new ways to write code quicker, make it more readable and faster, or just more fun. Here are some lesser-known tricks I've found and/or used myself.

Null checking

string result = variable1 ?? variable2 ?? variable3 ?? String.Empty;

You can use the ?? operator to check if a value is null and set a default value then, which is neat of its own. But you can also chain it to also check for other variables before resulting in a default value. Also, in C# 6 there is a new ?. operator you can use to quickly check for child properties:

string result = variable1?.childproperty?.childproperty ?? String.Empty;

Parsing a formula

var result = Convert.ToDouble(new System.Data.DataTable().Compute("(3*3)+1", null)); // 10

By using a bit of a creative trick of a method of the DataTable, you can parse simple formulas in your application. This can be useful when you want to support editable formulas in your application. For example to allow a reseller to customize their price based on an original prize: originalPrize * 1.2 + 1.

Making aliases for type names

using MyDictionary = Dictionary<string, List<int>>;

Put the above code outside your class declaration, and you'll be able to use "MyDictionary" as an alias. This can be useful when working with generics. They tend to make code unreadable quickly.


Sometimes when retrieving some specific information from the database, you want to cache it in case it needs to be requested again. But you don't want to store it forever in your memory. For example: Information about the current user doing a website request. By using the WeakReference class you can initialize your class with user information and allow the .NET garbage collector to unload it at any time it wishes (for example when it needs memory). Note the example below requires C# 4.5.

public class UserInfo
    public string RealName;

    private static Dictionary<string, WeakReference<UserInfo>> Cached =
        new Dictionary<string, WeakReference<UserInfo>>();

    public static UserInfo FromCache(string identity) {
        UserInfo userInfo;

        if (Cached.ContainsKey(identity) && Cached[identity].TryGetTarget(out userInfo))
            return userInfo;

        userInfo = new UserInfo()
            RealName = "" // Retrieve from database
        Cached[identity] = new WeakReference<UserInfo>(userInfo);

        return userInfo;

Example usage


Implementing operators in your class

You can implement the standard Math operators in your C# class. It looks like something idiotic to do, but it can actually turn out to be really useful. For example this is done with the default DateTime struct:

TimeSpan difference = new DateTime(2015,01,01) - new DateTime(2014,01,01);
// difference.TotalDays is 365

Another use case would be to quickly throw a few groups of people together like I've did in this example:

class Program
    static void Main(string[] args)
        var town1 = new GroupOfPeople("A");
        var town2 = new GroupOfPeople("B","C");
        var bothTowns = town1 + town2;
        // bothTowns.Names contains "A", "B", "C"

    public class GroupOfPeople
        public string[] Names;

        public GroupOfPeople(params string[] names)
            Names = names;

        public static GroupOfPeople operator +(GroupOfPeople a, GroupOfPeople b)
            return new GroupOfPeople()
                Names = a.Names.Concat(b.Names).ToArray()


The MethodImplAttribute attribute provides some useful things you can do. You can put it above Methods and Property accessors. 
By using [MethodImpl(MethodImplOptions.Synchronized)] you can make methods and properties thread-safe (Fields, those without {get; set;} are already thread safe).

In C# 3.5 and earlier, it does a lock(this) { }, however in newer C# versions it uses a different implementation without locks making it even faster to use. The use of this attribute can be compared with using the
synchronized keyword in java.

public class Bank {
    public double Balance
        private set;

    public void AddTransaction(double amount)
        if (amount + Balance < 0)
            throw new Exception("Not enough balance");
        Balance += amount;

To really micro-optimize your method calls, you can use [MethodImpl(MethodImplOptions.AggressiveInlining)] to make the compiler move a method implementation to the code calling it (reducing a method call). This can be useful for those small methods which needs to be called a lot of times, for example: When drawing frames in a game. Note that this won't save you that much time, but it is a fun trick nonetheless.

static double StartPosWhenCentering(double containerSize, double childSize)
    return (containerSize / 2) - (childSize / 2);


There is a lot of nice gems you can do with C#. Knowing a few of them will definitely make your days as a C# developer happier.

No comments:

Post a Comment