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:

using System.Text;
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.

using model = MyApp.Project.Model;

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

var m1 = new MyApp.Project.Model.Person();
var m2 = new OtherApp.Project.Model.Person(); 

You can use the following syntax:

using m1 = MyApp.Project.Model;
using m2 = OtherApp.Project.Model;
var p1 = new m1.Person();
var p2 = new m2.Person();
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.

using (var a = new SomeResourceType())
         //use the resource type

Its a simpler/efficient form for below code:

var a = new SomeResourceType();
        //use the resource type
        if (a != null)
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:

Dictionary<string, List<Dictionary<int, List>>>

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:

using System;

using myTypeName = System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<System.Collections.Generic.Dictionary<int, System.Collections.Generic.List<string>>>>;
namespace project{				
	public class Program
		public static void Main()
			var a = new myTypeName();
		private void MyMethod(myTypeName t) {

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

(Visited 102 times, 1 visits today)