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.
Generic is still an option if the two types derive from the same base or use the same interface, and no other classes use the base and/or interface.
Short of that, having the two overloads is the way to go.
Note: If you have .NET 4, you could make it a runtime thing and make the method dynamic.
In which case anything you throw at it will compile, but it will blow up at runtime if the
Nameproperty is not present.Personally, if I can’t modify the type to use a common interface, then I would go with the overloads and get compile-time safety.