Konrad Viltersten
Konrad Viltersten

Reputation: 39148

Extension method for precisely two different types

I'm using the code below. It's designed for a certain type to limit it's popup-ness in intellisense etc.

public static Generic Get<Generic>(this Entity input)
{
  return (Generic)input;
}

Now I'd like to use the same Get method for another type (or, to be fully covered, a few another types but still a fix number of). So I added a second method and the code looks as follows.

public static Generic Get<Generic>(this Entity input)
{
  return (Generic)input;
}

public static Generic Get<Generic>(this Entity2 input)
{
  return (Generic)input;
}

It strikes me that a better approach would be to keep it in the same method body and still cover all the regarded types. Is there a syntax for including e.g. two different types in the signature? Something like this pseudo-code below.

public static Generic Get<Generic>(this [Entity, Entity2] input)
{
  return (Generic)input;
}

The best approach I can think of, as shown below, consists of a entry method for each type and the logic in a private place. It makes sense when the logic is extensive but looks kind of superfluous when it's only a line or two.

public static Generic Get<Generic>(this Entity input)
{
  return CommonLogic(input);
}

public static Generic Get<Generic>(this Entity2 input)
{
  return CommonLogic(input);
}

private static Generic CommonLogic(Object input)
{
  return (Generic)input;
}

Upvotes: 8

Views: 1292

Answers (2)

LuckyLikey
LuckyLikey

Reputation: 3840

you could be doing something like that

    public static TSearch Get<TSource, TSearch>(this TSource obj) where TSource : BaseType, ISomeInterface
    {

    }

T can now only be of type BaseType and implementing ISomeInterface, but this would not make it aviable to be restricted to a fix count of supported classes

EDIT:

you now can use this on objects of Type BaseType implementing ISomeInterface and Return the Requested Type TSearch. However, you could also just use where TSource : ISomeInterface. The clue is that your Entityclasses implement this interface.

Check where - generic type constratint to understand how to use it.

Upvotes: 3

David Arno
David Arno

Reputation: 43254

C# doesn't support the [Entity, Entity2] notation, so that option is out.

If Entity and Entity2 share a common interface or base class, then declare it as:

public static Generic Get<Generic>(this IEntityCommon input)
{
    return (Generic)input;
}

If not and you have created Entity, Entity2 etc, then add a common interface. This interface need not define any methods and can be empty, it simply provides a common type for the extension method.

Failing all that, the "CommonLogic" way is your best option.

Upvotes: 6

Related Questions