Is there a generic constructor with parameter constraint in C#?

In C# you can put a constraint on a generic method like: public class A { public static void Method<T> (T a) where T : new() { //…do something… } } Where you specify that T should have a constructor that requires no parameters. I’m wondering whether there is a way to add a constraint … Read more

Why are arrays covariant but generics are invariant?

From Effective Java by Joshua Bloch, Arrays differ from generic type in two important ways. First arrays are covariant. Generics are invariant. Covariant simply means if X is subtype of Y then X[] will also be sub type of Y[]. Arrays are covariant As string is subtype of Object So String[] is subtype of Object[] … Read more

C# Create New T()

You can see what I’m trying (but failing) to do with the following code: protected T GetObject() { return new T(); } Any help would be greatly appreciated. EDIT: The context was as follows. I was playing around with a custom controller class for all controllers to derive from, with standardised methods. So in context, … Read more

foreach vs someList.ForEach(){}

There are apparently many ways to iterate over a collection. Curious if there are any differences, or why you’d use one way over the other. First type: List<string> someList = <some way to init> foreach(string s in someList) { <process the string> } Other Way: List<string> someList = <some way to init> someList.ForEach(delegate(string s) { … Read more