Background
A very quick post on a very easy to address C# error.
Error
Image
Text
‘Person’:type used in a using statement must be implicitly convertible to ‘System.IDisposable’.
Scenario #1
A very simple scenario.
We have a class called Person.
The class has a simple property called name.
We initialize the class and set its name property.
We print out that name by invoking Console.WriteLine.
Code
using System; public class Person { public string name { get; set; } } public class Program { public static void Main() { sayName(); sayNameCleanupExplicit(); } private static void sayName() { Person p1 = new Person(); p1.name = "Jay"; Console.WriteLine("My name is " + p1.name); } private static void sayNameCleanupExplicit() { Person p2 = new Person(); p2.name = "Brent"; Console.WriteLine("My name is " + p2.name); p2 = null; } }
Explanation
We have two methods above:-
- sayName
- sayNameCleanupExplicit
The only difference is that sayNameCleanupExplicit sets the object instance p2 to null.
Scenario #2
In our second scenario, we will like to automatically handle object deallocation.
Code
private static void sayNameCleanupImplicit() { using ( Person objPersonDisp = new Person() ) { objPersonDisp.name = "Tim"; Console.WriteLine ( "My name is " + objPersonDisp.name ); } }
Error
Once we add the “using statement“, we get the error we aforementioned.
And, the error reads:-
Image
Textual
error CS1674: 'Person': type used in a using statement must be implicitly convertible to 'System.IDisposable'
Error Signature
Depending on the version of the compiler you are using, the error’s signature may vary.
Here are some variants:-
- Microsoft (R) Visual C# Compiler version 4.8.4084.0
for C# 5- Syntax
- error CS1674: ‘<type>’: type used in a using statement must be implicitly convertible to ‘System.IDisposable’
- Example
- person.revised.cs(56,9): error CS1674: ‘Person’: type used in a using statement must be implicitly convertible to ‘System.IDisposable’
- Syntax
Remediation
To remediate is simple.
It involves:-
- Implement the IDisposable interface
- Override the Dispose method
Code
public class Person : IDisposable { public string name { get; set; } void IDisposable.Dispose() { } }
Summary
The disposition of the object’s instance takes slightly different tracks.
Original Class
- sayNameCleanupExplicit
- Disposition initiates upon setting the object’s instance to null
- sayName
- Disposition initiates upon exiting the method
Revised Class
- sayNameCleanupImplicit
- Disposition initiates upon closure of the using statement
References
- Microsoft
- C#
- using statement (C# Reference)
Link
- using statement (C# Reference)
- C#