c# generic and methods

  • Thread starter Thread starter Jure Bogataj
  • Start date Start date
J

Jure Bogataj

Hi all!

I was wondering if it is possible to create methods within generic classes,
based on what type class operates on:

e.g.

public class ListEx<T> : List<T>
{
public void MyMethod<int>(int param1, int param2)
{
}

public void MyMethod<string>(string param1, string param2)
{
}
}

So, MyMethod<int> would only be available if instance of class is declared:
ListEx<int>

and MyMethod<string> would only be available if class declared like:
ListEx<string>

Is this at all possible with generics?

Thanks in advance!

Best regards, Jure
 
No you can't overload generics methods like this.

Also you don't need to do this with generics.

You can create 2 methods like
public void MyMethod(int param1, int param2)
{
Console.WriteLine("int");
Console.WriteLine(param1.ToString());
Console.WriteLine(param2.ToString());
}
public void MyMethod(string param1, string param2)
{
Console.WriteLine(param1.ToString());
Console.WriteLine(param2.ToString());
}

and then you call them like this.

ListEx<string> list = new ListEx<string>();
list.MyMethod(4, 5);
list.MyMethod("a", "b");
 
I was wondering if it is possible to create methods within generic classes,
based on what type class operates on:

In your case, it sounds like it's a better idea to keep the class
generic and the methods nongeneric, like so:

class ListEx<T> : List<T> {
void MyMethod(T t) {
// ...
}
}

You can use generic constraints to define what types T ListEx will
accept.
 
Thank you both!

I've solved my problem using generic type (T) as type of parameters.

Best regards!
 
Back
Top