While learning about Generics I came to knew about Constraints on Type Parameters. One of these constraints is new() constraint. According to Microsoft:
The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.
Now I have a code like this.
using System;
namespace Test
{
class A { }
struct S { }
enum E { }
class Generics
{
public static void GenericMethod<T>() where T : new()
{
}
}
class Program
{
static void Main(string[] args)
{
Generics.GenericMethod<A>(); // Line 1
Generics.GenericMethod<S>(); // Line 2
Generics.GenericMethod<E>(); // Line 3
}
}
}
- Line 1 does not generate error bcoz classes have default parameterless constructor.
- Line 2 does not generate error bcoz structs have default parameterless constructor. And
- Line 3 does not generate error but WHY?
Why does new() constraint allows enum to be passed as type argument?
Also I am able to do this
E e = new E();
in the above code.
Does this mean enums have parameterless constructor by default?
Edited: After reading answers and comments I thought enums contain default constructor. So I used reflection to see if I can print on the console the default constructor of enum E. The code is as follows
Type T = typeof(E);
Console.WriteLine("Constructors");
ConstructorInfo[] constructors = T.GetConstructors();
foreach (var constructor in constructors)
{
Console.WriteLine(constructor.ToString());
}
But it doesn't prints anything.
So the question still remains Does an enum has a default parameterless constructor or not?