Primary constraints

1. How many type parameters the C# compiler allows to define?

2. What types can’t be used to specify generic type parameters constraints?

3. What are special primary constraints?

4. Which special type we cannot use a generic type constraint?

The C# compiler allows us to define several or zero generic type parameters. The System.Object, System.ValueType, System.Delegate, System.MulticastDelegate, System.Array, System.Enum, System.Void types cannot be used to specify generic type parameters.

Example 1:

        private static void PrimaryConstraintOfStream<T>() where T : Stream

        {

            //Cannot create an instance of the variable type ‘T’ because

            //it does not have the new() constraint

            //T temp = new T();

 

            T temp = null;

            temp.Close();

        }

 

 

Example 2:

        private static void PrimaryConstraintOfStruct<T>() where T : struct

        {

            //Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type.

            //Consider using ‘default(T)’ instead.

            //T temp = null;           

 

            T temp = new T();

        }

 

There are two special primary constraints the struct and the class. They allow us to define code special for reference type or value types for example we can assign null to a variable when we defined class as a primary constraint. Using class constraint we can use classes, interfaces, arrays, delegates. Using struct constraint we can use value types.

 

Example 3:

        //’System.IO.Stream?’ is not a valid constraint. A type used as a constraint must be an interface,

        //a non-sealed class or a type parameter.          

        private static void PrimaryConstraintOfNullable<T>() where T : Nullable<Stream>

        {

        }  

However it’s not possible to define a Nullable type as a type parameter, because it is defined as public struct Nullable<T> where T : struct, new() and the CLR wants to prohibit a recursife type such as Nullable<Nullable<T>>.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s