Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is a value type / reference type constraint useful in C#?

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.

like image 582
Oak Avatar asked Jan 19 '11 09:01

Oak


People also ask

What's the difference between a value type and a reference type?

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.

What is meant by value type and reference type in C#?

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.

What is the purpose of the class constraint on a type parameter?

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.

Which of the following constraint should be used to create a generic class that should only work with reference types?

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.


1 Answers

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.]

like image 125
Al Kepp Avatar answered Nov 15 '22 00:11

Al Kepp