Combining constraints of type struct and new () of a general type

Having recently , I had a reason to revise the Nullable documentation, I noticed that the Nullable definition looks like this:

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

I realized (wrong?) That structures always have an open constructor without parameters, if it is correct, which adds a constraint like new () here?

+6
source share
3 answers

For struct new it makes no sense. For classes, it does.

In your case, this is redundant.

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

It makes sense to indicate a new restriction in the case, such as above, but not when it is already limited by the structure.

The parameter constructor is smaller for value types - this is a C # restriction, not a CLI restriction. Perhaps that is why this once again indicates that there is room for maneuver in the future.

+1
source

It should not have a constructor without parameters, and even if it has one, it should not be publicly available. I believe that "new ()" requires it to have both.

Edit: as per MSDN documentation: "The new restriction indicates that any type argument in a generic class declaration must have a public constructor with no parameters .

+1
source

Just noting that this is indeed a validated IL (i.e.

  .class public sequential ansi sealed StructNewStruct`1<valuetype .ctor ([mscorlib]System.ValueType) T> extends [mscorlib]System.ValueType 

compiles like a simpler

  .class public sequential ansi sealed StructNewStruct`1<valuetype .ctor T> extends [mscorlib]System.ValueType 

), but I still do not have code that would do something else for them, which provides a simple where T:struct (or (Of T As Structure) in VB.NET and <valuetype T> in IL).

In particular, Nullable structures are no longer allowed for any general argument with a simple struct constraint. (It seems that Nullable objects are classes for almost all purposes except storage.)

So, in the end, Nullable<T> current (equivalent) where T:ValueType, struct, new() seems to be identical to where T:struct currently.

For your information, I used my updated DotLisp, which allows you to create generic types (only using MakeGenericType ) to try to create the StructNewStruct<t> and StructStruct<t> (*) types for all types in all 4.0 Framework builds that load "unusual" "assemblies (for example, System.Web may not have been loaded). (If there are any "special" types in assemblies of "obscure" frameworks, let me know and I guarantee that they are downloaded and tested.) All types with success or failure coincided with both structures.

(*) StructStruct<T> where T:struct

+1
source

Source: https://habr.com/ru/post/901866/


All Articles