c# generic and methods


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
 
Ad

Advertisements

?

=?iso-8859-9?Q?Bahad=FDr_ARSLAN?=

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");
 
U

UL-Tomten

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.
 
Ad

Advertisements

J

Jure Bogataj

Thank you both!

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

Best regards!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top