Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Using statement give an error even though my type implements IDisposable?

In my DataAccess project I have the code:

using (TandAEntities dataContext = new TandAEntities())
{
    // Some code
}

This gives no error and works fine.

But in my Unit Test project, I have that same code, but the compiler gives an error; type used in a using statement must be implicitly convertible to 'System.IDisposable'

I checked the definition by pressing F12, and it does indeed implement IDisposable, and has a dispose method.

Am I perhaps missing some references?

like image 328
Cloud9999Strife Avatar asked Jan 23 '13 06:01

Cloud9999Strife


People also ask

What does it mean when an object implements IDisposable?

Typically, types that use unmanaged resources implement the IDisposable or IAsyncDisposable interface to allow the unmanaged resources to be reclaimed. When you finish using an object that implements IDisposable, you call the object's Dispose or DisposeAsync implementation to explicitly perform cleanup.

What is using() in C#?

The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.

For what using ){ statement is used How is it related to IDisposable?

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

How do you know if a class implements IDisposable?

If a type implements the IDisposable interface, you should always call the Dispose method on an instance of the class when you are done using it. The presence of IDisposable indicates that the class has some resources that can be released prior to garbage collection.


1 Answers

Most likely answer in linked duplicate - missing using System.Data.Linq.

Other options: you have stale DLLs somewhere (i.e. installed in the GAC).

If you can't easily find stale DLL by just looking around and checking GAC - change code to something that uses this type but compiles and debug the test. Check Debug->Windows->Modules for location of the assembly with this type that is actually used.

like image 143
Alexei Levenkov Avatar answered Oct 29 '22 02:10

Alexei Levenkov