2.0: Generics, excluding value types

  • Thread starter Thread starter Jon Shemitz
  • Start date Start date
J

Jon Shemitz

Is there a way in 2.0 to say that a generic can not be applied to a
value type?

public class Unique<T> where T: new()
{
private static T cache = default(T);

public static T Instance
{ get
{
if (cache == null)
return cache = new T();
else
return cache;
} }
}

I want to be able to do Unique<someClass> but not Unique<int>.
 
Jon Shemitz said:
Is there a way in 2.0 to say that a generic can not be applied to a
value type?
Yeah, use the class constraint
public class Unique<T> where T : new(), class
{
//...
}
 
Daniel O'Connell said:
Yeah, use the class constraint
public class Unique<T> where T : new(), class

public class Unique<T> where T : class, new() // actually

Thanks! Either that's been added since "The C# Programming Language"
went to print or I just plain missed something.
 
Jon Shemitz said:
public class Unique<T> where T : class, new() // actually
Ya, I couldn't remember which order the new constraint had to be.
 
Back
Top