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:
public T myFunction<T>(int id, string name) where T : class1, new()
{
T obj = new T();
obj.id = id;
obj.name = name;
return obj;
}
This generic method requires type parameter T
to be derived from class1
and also to have a parameter-less constructor -- that's what the where T : class1, new()
means.
Since id
and name
properties are defined through the class1
base class, you can then set these to whatever was passed into myFunction
via its parameters.
Some more things to note about class1
:
class1
an interface instead of an abstract class, as it doesn't contain any functionality.id
, name
, type
need to be public if you actually want to be able to access them.public
. Consider using properties instead for that purpose.No, it's impossible, because all these classes are abstract
(can't be instantiated). We can't create an instance of an abstract class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With