USING-The .Net
Framework provides resource management for managed objects through the garbage collector - You do not have to
explicitly allocate and release memory for managed objects. Clean-up operations
for any unmanaged resources should be performed in the destructor in C#.
To allow the programmer to explicitly perform these clean-up
activities, objects can provide a Dispose method that can be invoked when the
object is no longer needed. The using
statement in C# defines a boundary for the object outside of which, the
object is automatically destroyed. The
using statement is exited when the end of the "using" statement block
or the execution exits the "using" statement block indirectly, for
example - an exception is thrown.
There is 2 use of using
statement. 1:- Importing namespace example:using
System; 2:- dispose the object using(SqlConnection oConnection=new
SqlConnection()) { oConnection.Open(); } if you won't close the connection it
will close the connection automatically once SqlConnection has been executed
completing.
The "using"
statement allows you to specify multiple resources in a single statement.
The object could also be created outside the "using" statement. The
objects specified within the using block must implement the IDisposable
interface. The framework invokes the Dispose method of objects specified within
the "using" statement when the block is exited.
Note:-
The UsingProgram class is not a part of the .NET Framework
and is only used in the example for demonstration. The UsingProgram class needs
to be released explicitly and implements the IDisposable interface.
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test
{
class UsingProgram:IDisposable
{
public void
Dispose()
{
throw new NotImplementedException();
}
public int ShowSum(int x, int y)
{
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
using (UsingProgram obj = new UsingProgram())
{
obj.ShowSum(2, 3);//herer you use this
}//here it
is release by using statement
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Test
{
class UsingProgram:IDisposable
{
public void
Dispose()
{
throw new NotImplementedException();
}
public int ShowSum(int x, int y)
{
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
UsingProgram obj = new UsingProgram();
using (obj)
{
obj.ShowSum(2, 3);//herer you use this
}//here it
is release by using statement
}
}
}
Note that the using
Directive in C# is different from the using statement. The "using"
Directive is used to provide an alias for a namespace.
No comments:
Post a Comment