So is it a class or what?

C# doesn’t stop to surprise me. While looking at Moq source code I noticed something strange:


Generic constraint says class but yet somehow interfaces account for class?

Technorati Tags: ,


Nate Kohari says:

Yeah, it’s a little confusing for sure. It’s just because there are two constraints related to the “kind” of type: class and struct. The former just means “reference type” and the latter means “value type”. I’m sure they did it to avoid adding more keywords to the language — which would really be a nightmare for reverse-compatibility.

Tuna Toksoz says:

How about the constraint new()
public class SomeClass where T:class,new()

looks ugly yet functional 🙂

Yes, it does the job, but not completely.

public class MyClass where T:class ,new(){}
public delegate void ImADelegate();

//somewhere else
var withDelegate = new MyClass();//won’t compile
var withInterface = new MyClass();//won’t compile
var withClass = new MyClass();//won’t compile

last line won’t compile, because string, although being a class doesn’t have parameterless constructor, and thats what new() demands.

Tuna Toksoz says:

Yes, right! I tend not to use it but there are times that you have to use it.
For example, since MVC framework doesn’t have any IoC stuff, they required me to use their method:
string RenderComponent(Expression> expr) where T:new()

then I believed in power of OSS and created a patch for MvcContrib which enables one to use IoC