Welcome to MSDN Blogs Sign in | Join | Help

Why is generic constructor not allowed?

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<T> 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.

 

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>();

        }

    }

}

Published Wednesday, September 19, 2007 10:08 PM by thottams@microsoft.com

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# MSDN Blog Postings &raquo; Why is generic constructor not allowed?

Wednesday, September 19, 2007 7:41 PM by MSDN Blog Postings » Why is generic constructor not allowed?

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker