Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Generic Method in C#

Tags:

c#

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

like image 814
Amira Elsayed Ismail Avatar asked Dec 06 '22 01:12

Amira Elsayed Ismail


2 Answers

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:

  • Consider making 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.
  • Usually, fields aren't actually exposed as public. Consider using properties instead for that purpose.
like image 75
stakx - no longer contributing Avatar answered Dec 14 '22 14:12

stakx - no longer contributing


No, it's impossible, because all these classes are abstract (can't be instantiated). We can't create an instance of an abstract class.

like image 45
Cheng Chen Avatar answered Dec 14 '22 15:12

Cheng Chen