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!!

  • Phylos

    IN the myTypeName declaration, the last List needs a type as in —

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

  • Phylos

    In my previous comment I noted that the last list was missing a type. Actually there’s more work to be done.instance To get it to compile, all the type collection names need to be fully qualified as in System.Collections.Generic.Dictionary or System.Collections.Generic.List. So the full declaration is —

    using myTypeName = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<System.Collections.Generic.Dictionary<int, System.Collections.Generic.List>>>;

    • Thanks for your inputs 🙂

      It needs two pre-conditions to be implemented:
      (1) Types used should be fully qualified.
      (2) Aliasing should be done outside namespace

      I am updating the code above accordingly.

      See compiled version on URL:

  • Alexandre Rodrigues do Nascime

    Very good post with clear language and usefull samples. Thx!