Aug 19

Using Generics in .Net

CSharpGenericsSmGenerics provide for extended code reusability and type safety in your projects.  A generic is a class, structure or interface that uses a type parameter as a placeholder for the actual type that it will contain or use.  These generic type definitions cannot be instantiated as they are not complete.

In its simplest form, it looks like this:

public class MyGeneric<T>
    public T Field;

Once you have created a generic type definition, your next step is to create an instance of it- at which point you will specify the type that will be used – for this instance only.

    class Program
        static void Main(string[] args)
            MyGeneric<string> StrGen = new MyGeneric<string>();
            StrGen.Message = "Hello World";
            MyGeneric<int> IntGen = new MyGeneric<int>();
            IntGen.Message = 1234;

    class MyGeneric<T>
        public T Message { get; set; }

        public void OutputMsg()

In this example, when we instantiated the class, we set the generic type parameter to ‘string’.  We now have a strongly typed object and the compiler will throw an error if a value other than a string is passed in.

By using generics, we increase the reusability of a custom type (instead of having one for int, one for strings and one for doubles) while still maintaining a type safe system.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>