Extension Method for Two Different Types

I am using the code below. It is intended for a specific type, to limit its tooltip in intellisense, etc.

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

Now I would like to use the same Get method for another type (or, to be fully covered, several other types, but still a number of fixes). So I added a second method, and the code is 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 seems to me that the best approach would be to keep it in the same method and still cover all the types in question. Is there a syntax to include, for example, two signature signatures? Something like this pseudo code below.

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

The best approach that I can think of, as shown below, consists of an input method for each type and logic in a private place. This makes sense when the logic is extensive, but looks redundant when it is 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; } 
+7
c # extension-methods
source share
2 answers

C # does not support the [Entity, Entity2] notation, so the option is missing.

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

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

If not, and you created Entity , Entity2 , etc., add a common interface. This interface does not have to define any methods and may be empty; it just provides a generic type for the extension method.

Otherwise, the "CommonLogic" path is your best bet.

+5
source share

you can do something like this

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

T can now only be of type BaseType and implementation of ISomeInterface , but this does not make it available to limit the number of fixed supported classes

EDIT:

now you can use this on BaseType objects that implement ISomeInterface and return the requested TSearch type. However, you can also use where TSource : ISomeInterface . The key is that your Entity classes implement this interface.

Note where is the generic constratint type to understand how to use it.

+3
source share

All Articles