Click here to Skip to main content
15,892,537 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to use a class statement: MDFtoMDF.cs but I do not know how to write a "using" statement connecting the class to MDFtoMDF.aspx.cs. Could someone help?

MDFtoMDF.cs
C#
public class MDFtoMDF
{
    public int cid { get; set; }
    public string cdt { get; set; }
    public string cc1 { get; set; }
    public string cc2 { get; set; }
    public string cc3 { get; set; }
}


MDFtoMDF.aspx.cs
using ????
C#
cid idc = new cid();
cdt dt = new cdt();
cc1 c1 = new cc1();
cc2 c2 = new cc2();
cc3 c3 = new cc3();


...Working code
C#
using (SqlDataReader dr = cmd.ExecuteReader())
{
     dr.Read();
     n += 1;
     idc.Add(dr[0]);
     dt.Add(dr[1]);
     c1.Add(dr[2]);
     c2.Add(dr[3]);
     c3.Add(dr[4]);
                            
}
Posted
Updated 5-Sep-14 22:14pm
v2

1 solution

A using statement works on classes that implements the interface IDisposable.
And the dispose method should release all allocated resources, e.g. close open files, delete memory etc.

Implementing your example in two different ways. The end result is the same.
Not using using:
C#
SqlDataReader dr = null;
try
{
    dr = cmd.ExecuteReader())
    {
        dr.Read();
        n += 1;
        idc.Add(dr[0]);
        dt.Add(dr[1]);
        c1.Add(dr[2]);
        c2.Add(dr[3]);
        c3.Add(dr[4]);  
    }
}
finally
{
    // Always close, even if an exception occurs
    if (dr != null)
        dr.Close();
}


using used:
C#
using (SqlDataReader dr = cmd.ExecuteReader())
{
    dr.Read();
    n += 1;
    idc.Add(dr[0]);
    dt.Add(dr[1]);
    c1.Add(dr[2]);
    c2.Add(dr[3]);
    c3.Add(dr[4]);  
} // The dispose method is called upon leaving the scope


So you need to implement the IDisposable interface in your class
C#
public class MDFtoMDF : IDisposable
{
    public int cid { get; set; }
    public string cdt { get; set; }
    public string cc1 { get; set; }
    public string cc2 { get; set; }
    public string cc3 { get; set; }

    public void Dispose()
    {
        Dipsose(true);
    }

    private void Dispose(bool disposable)
    {
        if (disposable)
        {
            // Free resources
        }
        // Prevents the destructor to be called if dispose is called.
        GC.SuppressFinalize(this);
    }
}


Now you can write the code as below
C#
using (MDFtoMDF test = new MDFtoMDF())
{
    // Do your stuff
}


The thing is that if you don't have resources that must be explicitly released, then the using statement does not add any useful functionality.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900