Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

one method, different parameters

If I have a function that does some operations (that work for either one of two types) and needs to work for two different type parameters, is there some nice way to make something like public void foo(typeX x || typeY x)?

Example:

void main(bool b)
{
    if(b)
    {
        List<int> x = new List<int>();
        x.Add(5);
    }
    else
    {
        Collection<int> x = new Collection<int>();
        x.Add(5);
    }
    foo(x);
}

The way I see it, this leaves two options.

option1:

void foo(List<int> x)
{
    Console.WriteLine(x.ToString());
}

void foo(Collection<int> x)
{
    Console.WriteLine(x.ToString());
}

Why not? Because if void foo()is longer than just a few rows it seems ugly and unnecessary.

option2:

void foo(Object x)
{
    Console.WriteLine(x.ToString());
}

Why not? Works fine for this simple example, but If foo is supposed to do something that not EVERY object has, like x.Add(1); we get an error saying that Object doesn't have that method.

Does anyone know some geniusly gorgeous sollution for this? or am I stuck with option1?

Upvotes: 0

Views: 58

Answers (1)

lc.
lc.

Reputation: 116438

In this case List<int> and Collection<int> both implement the IList<int> interface (among others). So, assuming the code is not specific to one or the other of these types, you should be able to use the interface:

void foo(IList<int> x)
{
    Console.WriteLine(x.ToString());
}

The generalized version of this answer - which applies for classes you write - is you should create an interface for the types in question. Assuming you have a TypeX and TypeY as you state in the beginning of the question:

interface ICanFoo
{
    string Foo();
}

class TypeX : ICanFoo
{
    public string Foo()
    {
        return "I'm a TypeX!";
    }
}

class TypeY : ICanFoo
{
    public string Foo()
    {
        return "I'm a TypeY!";
    }
}

void foo(ICanFoo x)
{
    Console.WriteLine(x.Foo());
}

Upvotes: 2

Related Questions