Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a method take 2 different types

I know this is probably a really simple question but I'm having a brain fart at the moment. I am trying to create a method that can take one of 2 custom types. Basically the body of this method will be identical for both the types as they both have a Name property (I'm doing a comparison on the Name property to use in sorting). How should I do this?

My first thought was just to overload the method with the two types as arguments:

int Compare(Type1 first, Type1 second)
int Compare (Type2 first, Type2 second)

but the body of the methods ended up being identical thus it seems like a waste.

My next thought was to use generics but that doesn't seem right because I'm not really making it generic as it can only be used with 2 specific types.

Clarification: The "custom" types are actually not my custom types. What I meant was taht they are not built-in types. I do not have control over what is in these types or the inheritence hierarchy. They just both happen to have the Name property.

like image 277
KrisTrip Avatar asked Nov 29 '22 18:11

KrisTrip


1 Answers

Oddly enough so far no one has posted what seems to me to be the obvious choice: take the name as the argument of the comparison. Make the caller get the name property out of the object. If all the method needs to use is the name then why are you passing in the rest of the object?

If you need to abstract over the notion of "I can get a name out of this thing" then do that:

Example:

int Compare(string name1, string name2) { ... whatever ... }
int Compare<T>(T t1, T t2, Func<T, string> getName)
{
    return Compare(getName(t1), getName(t2));
}

And now you can say:

Compare(car1, car2, c=>c.Name);
Compare(employee1, employee2, e=>e.Name);

and so on.

like image 167
Eric Lippert Avatar answered Dec 05 '22 05:12

Eric Lippert