Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have a problem with generic type. I tried to make one generic class and then some classes that have constructor with parameter(s).

Problem
--------
When i'll try to invoke method from generic class, the error was occurred.
This is for the code :

XML
public class Test
{
    public Test(string a)
    {
        //todo..
    }
}

public class Test2
{
    public Test(string a, int b)
    {
        //todo..
    }
}

public Generic<T> where T : class, new()
{
    public bool Save(T t){
        //todo..
        return blah...
    }

}

var result = new Generic<Test>().Save(blahhh);


Error :
must be a non-abstract type with a public parameterless constructor in order to use it as parameter T in the generic type



Please help me.. :( Thanks
Posted
Updated 19-Jun-12 18:26pm
v4
Comments
Ganesan Senthilvel 20-Jun-12 0:24am    
To avoid this error, make sure that the type has the correct constructor, or modify the constraint clause of the generic type or method.

1 solution

First of all, your code that you published had a ton of errors: This compiles:

SQL
public class Test
{
    public Test(string a)
    {
        //todo..
    }
}

public class Test2
{
    public Test2(string a, int b)
    {
        //todo..
    }
    public Test2();
}

public class Generic<T> where T : class, new()
{
    public bool Save(T t)
    {
        //todo..
        return true;
    }
}


This will now compile:

var result = new Generic<test2>().Save(new Test2("dfd", 2));</test2>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900