Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining struct and new() generic type constraints

Having recently had reason to peruse the Nullable documentation, I noticed that the definition of Nullable looks like:

public struct Nullable<T> where T : struct, new()

I was of the (mis?)understanding that structs always have a public parameterless constructor, if this is correct, what does the new() type constraint add here?

like image 577
Rich O'Kelly Avatar asked Nov 19 '11 00:11

Rich O'Kelly


1 Answers

For struct new doesn't make sense. For classes it does.

In your case it is a redundant.

public T FactoryCreateInstance<T>() where T : new()
{
return new T();
}

It make sense to specify new constraint in a case like above but not when it is already constrained to be struct.

Parameter less constructor for value types is a C# restriction and not a CLI restriction. Maybe this is why is it specified redundantly to leave some wiggle room for future.

like image 82
parapura rajkumar Avatar answered Oct 24 '22 21:10

parapura rajkumar