using: A Wonder C# keyword

If you are a C# developer you probably have seen and used the using keyword many many times but there are different variations of using the using ! that you may haven’t seen.

Usage#1: Import types defined in namespaces

This is probably what you are using 100’s times a day, it allows the use of types in a namespace:

Usage#2: Assign an alias to the namespace or type

This is also useful when you have a type with same name it two different namespaces.

So, then instead of repeating namespaces like this in your code:

You can use the following syntax:

Usage#3: As a statement to Use/Dispose object

It provides a convenient syntax that ensures the correct use of IDisposable objects. In simple words it defines a scope at the end of which an object will be disposed.

Its a simpler/efficient form for below code:

Usage#4: “using” Directive to alias complex types

This is another usage of “using” that I haven’t seen many developers are aware of. Imaging you need to work with a complex long type like:

and you need to repeat this in several places in your code. Wouldn’t code look clumsy and confusing? Indeed!!

Instead you can define an alias for this long type string and use the alias wherever you need it as below:

It needs two pre-conditions to be implemented:

  1. Types used should be fully qualified.
  2. Aliasing should be done outside namespace

Is it amazing….

Enjoy cleaner code!!