NetInverse Developers Blog

March 9, 2009
Category: .Net — Tags: , , — admin @ 12:16 am

Following code doesn’t compile:

    class GenericFactory where T : new()
    {
        public T Create(object a, object b)
        {
            return new T(a, b);
        }
    }

The compiler will give you following error message: “‘T’: cannot provide arguments when creating an instance of a variable type.”. Well, there are a couple ways to solve this issue.

Use reflection

    class GenericFactory
    {
        public T Create(object a, object b)
        {

            return (T) typeof(T).GetConstructor(
   new System.Type[] { typeof(object), typeof(object) }).Invoke(new object[] {a, b});
        }
    }

Use intialization

Following code uses an initialization interface to solve this issue. You can also use properties instead of a method.

    interface I
    {
        void Initialize(object a, object b);
    }

    class GenericFactory where T : I, new()
    {
        public T Create(object a, object b)
        {
            T t = new T();
            t.Initialize(a, b);
            return t;
        }
    }

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

©2009 NetInverse. All rights reserved. Powered by WordPress