5 Powerful Ways to Use the using Keyword in C#

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 not have 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
        ....
}

It’s a simpler and more efficient form for below code:

var a = new SomeResourceType();
try
{
        //use the resource type
        ....
}
finally
{
        if (a != null)
            ((IDisposable)a).Dispose();
}

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

Usage #5: C# 8.0 “using declarations”

Since C# 8.0 (released in 2019), using can be written as a declaration rather than a statement block:

using var file = new StreamReader("file.txt");
// file is disposed automatically at the end of the scope

Using aliases for complex types simplifies maintenance and reduces errors.

(Visited 517 times, 1 visits today)