Jean Hibbert's Blog

.NET Framework, SQL Server and other random thoughts.

Generic type usage-constraints

Since the release of the .Net Framework 2.0 the amount of code I've had to write when building utility functions has diminished greatly. There is only one thing I enjoy more than writing code, and that is deleting code. :) I get to do that a lot nowadays especially when working on legacy .Net Framework 1.0/1.1 projects.

Take a look below and see how I've managed to reduce two functions which are screen specific to one.

    

       // Duplicated in GetFormAInstance

        public static screens.FormB GetFormBInstance(string key, out bool alreadyExists)

        {

 

            screens.FormB form = Controller.GetRegister.Get(key) as screens.FormB;

 

            if (form == null)

            {

                alreadyExists = false;

                form = new screens.FormB();

                Controller.GetRegister.Register(key, form);

            }

            else

            {

                alreadyExists = true;

                form.BringToFront();

            }

 

            return form;

        }

 

        // Duplicated in GetFormBInstance

        public static screens.FormA GetFormAInstance(string key, out bool alreadyExists)

        {

 

            screens.FormA form = Controller.GetRegister.Get(key) as screens.FormA;

 

            if (form == null)

            {

                alreadyExists = false;

                form = new screens.FormA();

                Controller.GetRegister.Register(key, form);

            }

            else

            {

                alreadyExists = true;

                form.BringToFront();

            }

 

            return form;

        }

 

        // Function which uses generics to encapsulate GetFormAInstance and GetFormBInstance

        public static T GetFormInstance<T>(string key, out bool alreadyExists) where T : Form, new()

        {

 

            T form = Controller.GetRegister.Get(key) as T;

 

            if (form == null)

            {

                alreadyExists = false;

                form = new T();

                Controller.GetRegister.Register(key, form);

            }

            else

            {

                alreadyExists = true;

                form.BringToFront();

            }

 

            return form;

        }

 

 

As you can see I am using the ability to define constraints on Type parameters to indicate that the Type returned from GetFormInstance will support the new() constraint and the type will derive from the Form class. If I had not supplied this constraint information the compiler would have have complained about the "form = new T();" line and given me the following error : "Cannot create an instance of the variable type 'T' because it does not have the new() constraint".