Thottam R. Sriram MSDN blog archive · 2006–2009

Why is generic constructor not allowed?

original post

Generic argument is not allowed in the constructor. When I compile the code below I get a compilation error saying:

error CS1519: Invalid token '(' in class, struct, or interface

member declaration

The reason is simple. You can have a class Foo and a class Foo as described in my previous post. Now when you says

fooInstance = new Foo<T>();

there is no way for the compiler to find out the right class constructor to call.

C#
namespace Sample
{
    using System;
    public class Foo <T>
    {
    }
    class Foo
    {
        public Foo<T>()
        {
            Console.WriteLine("This is generic Foo class {0}",typeof(T));
        }
    }
    public class Bar
    {
        static public void Main()
        {
            Foo fooGenericInstance;
            fooGenericInstance = new Foo<Int32>();
        }
    }
}

Comments

← All posts