A question regarding generics
Here is the code,
Code:
namespace ConsoleApplication1
{
class A<T> where T:IDisposable
{
};
class Program
{
static void Main(string[] args)
{
A<int> a = new A<int>();
}
}
}
There is a compiler error "The type 'int' cannot be used as type parameter 'T' in the generic type or method 'ConsoleApplication1.A<T>'. There is no boxing conversion from 'int' to 'System.IDisposable'.". I thought the interface could be either value or reference type. Why'd I need boxing here? Thanks.
Re: A question regarding generics
The error is telling you that an int isn't an IDisposable type. You have defined a constraint where T must implement the IDisposable interface. Obviously passing in a type that doesn't implement IDisposable is going to fail the constraint. The is the part of the recurring theme where I encourage you to write code.
What happens if you define the class as?
Code:
class A<T> where T : class { }
or
Code:
class A<T> where T : struct { }
or
Code:
class A<T> where T : object { }
Re: A question regarding generics
Quote:
Originally Posted by
Arjay
The error is telling you that an int isn't an IDisposable type. You have defined a constraint where T must implement the IDisposable interface. Obviously passing in a type that doesn't implement IDisposable is going to fail the constraint. The is the part of the recurring theme where I encourage you to write code.
What happens if you define the class as?
Code:
class A<T> where T : class { }
or
Code:
class A<T> where T : struct { }
or
Code:
class A<T> where T : object { }
Thanks. I thought int can be converted to IDisposable implicitly.
Re: A question regarding generics
Quote:
Originally Posted by
LarryChen
Thanks. I thought int can be converted to IDisposable implicitly.
Take a look at the definition for int (or any value type) in MSDN. To determine if an object has implemented IDisposable, walk up the inheritance hierarchy and see if IDisposable is declared anywhere under the syntax section.
For example, the syntax for int (doesn't implement IDisposable):
Code:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable,
IConvertible, IComparable<int>, IEquatable<int>
Syntax for SqlConnection (does implement IDisposable)
Code:
public sealed class SqlConnection : DbConnection,
ICloneable
Jumping up a level to inspect DbConnection yields
Code:
public abstract class DbConnection : Component,
IDbConnection, IDisposable