Question

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?

Was it helpful?

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.

OTHER TIPS

The purpose of "using" is to ensure Dispose() is called on an object that implements IDisposable. Therefore, the best way to use using keyword in your code is, like in any other code, on objects that implement IDisposable. This could be, for example, your "newTempUser" or your "container". Since we do not have access to their definitions, only you can answer this question.

There aren't really good and bad uses of using. Either you use it or you don't. If you don't use it when instantiating a class implementing IDisposable then you've likely made a mistake (unless you have some good reason for calling Dispose yourself elsewhere which is a very small percent of use cases).

If you fail to use it then the point when the resource is disposed of is less predictable and it will likely have negative effects on your applications performance. There aren't different ways of using it, there is only one;

using (ClassImplementigIDisposable instance = new ClassImplementigIDisposable()) 
{ 
     // code that uses instance
     // at the end of this block `Dispose` will be called on instance 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top