I have the following structure:
public enum MyTypes
{
Type1 = 1,
Type2 = 2,
Type3 = 3
}
public abstract class class1
{
int id;
string name;
MyType type;
}
public class class2 : class1
{
}
public class class3 : class1
{
}
public class class4 : class1
{
}
now what I want to do is to make a generic method , I want to give it the type of object say class 3 and it will create object from class 3 and define it’s variables and return it to be able to add it to a list of class1
like that
private class1 myFunction (MyType t , int id , string name)
{
T obj = new T();
obj.type = t ;
obj.id = id ;
obj.name = name;
return obj;
}
how to create this generic method ?
please Help me as soon as you can
Thanks in Advance
As Danny Chen says in his answer, you will have to modify your class definitions a little for it to work, then you could do something like the following:
This generic method requires type parameter
Tto be derived fromclass1and also to have a parameter-less constructor — that’s what thewhere T : class1, new()means.Since
idandnameproperties are defined through theclass1base class, you can then set these to whatever was passed intomyFunctionvia its parameters.Some more things to note about
class1:class1an interface instead of an abstract class, as it doesn’t contain any functionality.id,name,typeneed to be public if you actually want to be able to access them.public. Consider using properties instead for that purpose.