-
July 2nd, 2013, 03:12 PM
#1
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.
-
July 3rd, 2013, 11:36 AM
#2
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 { }
-
July 3rd, 2013, 12:07 PM
#3
Re: A question regarding generics
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.
-
July 3rd, 2013, 02:07 PM
#4
Re: A question regarding generics
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|