Translate

Wednesday, October 24, 2012

C# using tutorial



The keyword using in C# has different meanings based on the context in which you use it.

using directive
When you see this on the top of a C# code page

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

what you are doing is qualifying the namespace.The advantage of doing this is that, instead of typing
 System.Console.WriteLine("Hello, World!");
  you could instead add  using System; on the top of the page and then just type
Console.WriteLine("Hello, World!");


Basically it saves you some typing and your code would be easier to read.
Note: You CANNOT qualify a class this way. This is only meant for qualifying namespaces.


using statement

using (GetDataFromFile GF = new GetDataFromFile())
{
    data = GF.ReadFile();
}

This code is equivalent to 
try
{             
    data= GF.ReadFile();
}
finally
{
    GF.Dispose();
}

When you use a using statement, all you are doing is telling the .net runtime to call the Dispose method after the execution of the code inside the braces. The dispose method gets called even if the code inside the braces throws an error.

1 comment:

Comments will appear once they have been approved by the moderator