Constructor constraints

1. What are the construct constraints?

When we declare the construct constraint we promise to compiler that a specified type will be non-abstract class having parameterless constructor. We can’t use the struct constraint with the new() constraint because it is redundant.

Example 1:

    class ConstrainedConstructor<T> where T : new()

    {

        public T CreateObject()

        {

            return new T();

        }

    }

    //The ‘new()’ constraint cannot be used with the ‘struct’ constraint

    class StructRedundand<T> where T : struct, new()

    {

        public T CreateObject()

        {

            return new 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