When is type / reference type type restriction used in C #?

I am looking for simple examples demonstrating when type / reference type constraints are useful.

... where T : struct // when is this useful? ... where T : class // and what about this? 

I remember seeing some good examples in the past, but I just can't find them.

+6
generics c # constraints
source share
3 answers

It allows you to use the as operator on T if it is T:class .

This prevents you from comparing T with null if T is T:struct .

Note that if you omit T:class , you can compare T with zero, even if T is a value type.

[Note. I had to edit this post several times before it became correct. At least I hope this is correct now.]

+11
source share

The main utility I found in it is Marshalling and pinning an object in memory.

For example, I do a lot of work with internal structures that cannot be automatically converted or sent via wiring as a byte stream, so I wrote this helper:

 public static T PinAndCast<T>(this Array o) where T : struct { var handle = System.Runtime.InteropServices.GCHandle.Alloc(o, GCHandleType.Pinned); T result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return result; } 
+1
source share

"T: class" will force the generic type specified as a class, not a value. For example, we can create an ObjectList class that requires the generic type to be specified as a class, not a value:

 class ObjectList<T> where T : class { ... } class SomeObject { ... } ObjectList<int> invalidList = new ObjectList<int>(); //compiler error ObjectList<SomeObject> someObjectList = new ObjectList<SomeObject>(); //this works 

This forces an invariant of your generic type T, which might otherwise be invalid. "T: struct" will work the same. Note that you can also use this construct to enforce not only that the type T is a class, but also that it matches the interface. The sample code I used also has

 class MyList<T> where T : class, IEntity { ... } 

which makes T be a class AND is also IEntity.

-one
source share

All Articles