Search code examples
c#.netusing

How is "using" statement supposed to work?


I'm trying to take advantage of the using statement in the following code:

Uri uri = new Uri("http://localhost:50222/odata"); 
var container = new CourseServiceRef.Container(uri);

CourseServiceRef.NotNeeded newTempUser = new CourseServiceRef.NotNeeded()
    { 
       Email = model.UserName,
       Username1 = model.UserName 
    };             
container.AddToNotNeededs(newTempUser);
container.SaveChanges();

However this doesn't compile. Why?


Solution

  • using statement - not to be mingled with using directive - is meant for objects that implement the IDisposable interface so that they're disposed of automatically at the end of the code block:

    using (var toto = new MyDisposableClass())
    {
        // do stuff
    }
    

    If any of your classes do implement this interface (or inherit from something that does), you may use the above syntax to ensure call to Dispose() method. You cannot use using blocks for objects that does not implement this interface, it simply won't compile.

    Essentially, this will be doing the same as the following:

    var toto = new MyDisposableClass()
    
    try
    {
        // do stuff
    }
    finally
    {
        if (toto != null) ((IDisposable)toto).Dispose();
    }
    

    The only difference here would be that in the first scenario, toto's scope dies at the end of the using block.