Ques:- Can i write own classes under using statement
The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
Yes, i can write own classes under using statement if the class implements IDisposable interface other wise it will gives error on compile time-
//XYZ: type used in a using statement must be implicitly convertible to System.IDisposable
Here XYZ is class name
Exp:- 1
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanWriteCustomClassInUsingStatement
{
class XYZ
{
public void show()
{
Console.WriteLine("Testing..");
}
}
class Program
{
static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection())
{
}
//for SqlConnection its perfectly works
//throws error at compile time
/ /XYZ: type used in a using statement must be implicitly convertible to System.IDisposable
using (XYZ x= new XYZ())
{
}
}
}
}
It internally generates code similar to-
The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
Yes, i can write own classes under using statement if the class implements IDisposable interface other wise it will gives error on compile time-
//XYZ: type used in a using statement must be implicitly convertible to System.IDisposable
Here XYZ is class name
Exp:- 1
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanWriteCustomClassInUsingStatement
{
class XYZ
{
public void show()
{
Console.WriteLine("Testing..");
}
}
class Program
{
static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection())
{
}
//for SqlConnection its perfectly works
//throws error at compile time
/ /XYZ: type used in a using statement must be implicitly convertible to System.IDisposable
using (XYZ x= new XYZ())
{
}
}
}
}
to remove error class XYZ should be implemented IDisposable interface and implements dispose method.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CanWriteCustomClassInUsingStatement
{
class XYZ : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
public void show()
{
Console.WriteLine("Testing..");
}
}
class Program
{
static void Main(string[] args)
{
using (SqlConnection con = new SqlConnection())
{
}
// Now It works perfectly
using (XYZ x= new XYZ())
{
}
}
}
}
It internally generates code similar to-
XYZ t = new XYZ ();
try {
t.
show();
}
finally {
t.Dispose();
}
No comments:
Post a Comment