Generics - Constraints

Generics - Constraints

Definition

When you define a generic class, you can apply restrictions to the kinds of types that client code can use for type arguments when it instantiates your class. If client code tries to instantiate your class by using a type that is not allowed by a constraint, the result is a compile-time error.  [MSDN]

where T: struct     


The type argument must be a value type. Any value type except Nullable can be specified. 

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

where T : new()

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

where T :<base class name>

The type argument must be or derive from the specified base class.

where T :<interface name>

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. 

Code

Constraints.cs

public class Compare<DONTKNOWYET>
{
        public bool CompareData(DONTKNOWYET d1, DONTKNOWYET d2 )
        {
            if(d1.Equals(d2))
            {
                return true;
            }
            return false;
        }
}

Program.cs

 class Program
 {
        static void Main(string[] args)
        {

            Compare<int> intCompare = new Compare<int>();
            Compare<string> stringCompare = new Compare<string>();


            // Compare equal numbers
            Console.WriteLine("3=3: ? ");
            if (intCompare.CompareData(3, 3))
            {
                Console.WriteLine("Entered data is Equal!");
            }
            else
            {
                Console.WriteLine("Entered data is not Equal!");
            }

            // Compare unequal numbers
            Console.WriteLine("3=10: ? ");
            if (intCompare.CompareData(3, 10))
            {
                Console.WriteLine("Entered data is Equal!");
            }
            else
            {
                Console.WriteLine("Entered data is not Equal!");
            }


            // Compare equal string
            Console.WriteLine("BYTERODEO=BYTERODEO: ? ");
            if (stringCompare.CompareData("BYTERODEO", "BYTERODEO"))
            {

                Console.WriteLine("Entered data is Equal!");
            }
            else
            {
                Console.WriteLine("Entered data is not Equal!");
            }

            // Compare unequal string
            Console.WriteLine("RODEOBYTE=BYTERODEO: ? ");
            if (stringCompare.CompareData("RODEOBYTE", "BYTERODEO"))
            {
                Console.WriteLine("Entered data is Equal!");
            }
            else
            {
                Console.WriteLine("Entered data is not Equal!");
            }

            Console.Read();

        }
 }

Output


Advantages

  • Generics are Type Safe and eliminates overhead of multiple implementations. 
  • Generics does not require boxing and unboxing.
  • Generics are checked on compile time so your code will be always correct at run time. 
  • Generics provide type constraints which helps you control the types that can be given as input to your class\method.

Disadvantages

  • Code becomes complex for beginners.
  • Generic types can be derived from most base classes, such as MarshalByRefObject (and constraints can be used to require that generic type parameters derive from base classes like MarshalByRefObject). However, the .NET Framework does not support context-bound generic types. A generic type can be derived from ContextBoundObject, but trying to create an instance of that type causes a TypeLoadException.

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)