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.
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.
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
Comments
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.
How about the constraint new() where T:class,new()
public class SomeClass
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();//won’t compile();//won’t compile();//won’t compile
var withDelegate = new MyClass
var withInterface = new MyClass
var withClass = new MyClass
last line won’t compile, because string, although being a class doesn’t have parameterless constructor, and thats what new() demands.
Yes, right! I tend not to use it but there are times that you have to use it.(Expression> expr) where T:new()
For example, since MVC framework doesn’t have any IoC stuff, they required me to use their method:
string RenderComponent
then I believed in power of OSS and created a patch for MvcContrib which enables one to use IoC