I'm looking for simple examples that demonstrate when the value type / reference type constraints are useful.
... where T : struct // when is this useful?
... where T : class // and what about this?
I remember seeing some very nice examples in the past but I just can't find them.
There are two kinds of types in Visual Basic: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data.
A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data. Reference Type variables are stored in the heap while Value Type variables are stored in the stack.
Object, you'll apply constraints to the type parameter. For example, the base class constraint tells the compiler that only objects of this type or derived from this type will be used as type arguments. Once the compiler has this guarantee, it can allow methods of that type to be called in the generic class.
Reference type constraint This type of constraint specifies that the type argument should be a reference type. If we try to substitute a non-reference type for the type argument then we will get a compile-time error.
It allows you to use as
operator on T if it is T:class
.
It forbids you to compare T with null
if T is T:struct
.
Note that if you omit T:class
then you can compare T to null even when T is a value type.
[Note: I needed to edit this post a few times before it got correct. At least I hope it is now correct.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With