Tips and Tricks of C#


I, C# developer, know the basics of C# like, declaration, condition, loops, operators, generics, anonymous types, lambdas, LINQ. Some of features there are in C# that I don’t know if it was there before I look at a stackoverflow question (Hidden Features of C#). In that question there are many answer that show how to use those features. You must visit that because you are a C# developer and you should know about that.

This article inspired by that question, as I became fan of some features.

Null Comaprison

As tradition I always comparing null like

But using ?? (null-coalescing operator) we can easily compare for null

Even we can chain the ?? operator so that you can do a bunch of null comparisons.


Previously when I combined two string to form a path I always did adding two string

By using Path.Combine() method it is easy to form a path and would be less error prone:

Aliased generics

Suppose you have to use a really complex generic in your code like:

and what if it need more time to declare in code, you have to write to duplicate code each time.
So if you use aliasing like:

as keyword

We always need to casting a object to a Type, and when we don’t know what is the type of object which is to be cast, we should use as keyword like:

rather than

because first one return null if obj isn’t a MyClass while first one throw cast exception in this case.

params keyword

When I don’t know how many parameter is passed in a method then I use params like

Static constructors

MSDN says

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Iterate over dictionary

Object Intializer

I was used to initialize object like

But C# provide a greater way to inialize object with its value in much readable and clearer syntax

Collection Initalizers

Many programmer always initialize collection like this.

This is not wrong, but C# provide a syntax for initialize collection like:

More Tips coming soon…

Want to hear from you…

Happy Reading 🙂


2 thoughts on “Tips and Tricks of C#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s