Extension method restricted to objects containing specific properties

Is there a way to create an extension method whose parameter constraint has properties with specific names. eg:.

public static bool IsMixed<T>(this T obj) where T:?
{
    return obj.IsThis && obj.IsThat;
} 

I tried to declare objdynamic, but this is not allowed.

+3
source share
4 answers

This feature is often called duck print. (Because when you call foo.Quack (), all you care about is that it dodges the duck.) Non-dynamic duck printing is not a feature of C #, sorry!

If you really don't have information about the type of the argument, you can use dynamic in C # 4:

public static bool IsAllThat(this object x)
{
    dynamic d = x;
    return d.IsThis || d.IsThat;
}

But it would be better to come up with some kind of interface or some such thing that describes types at compile time.

+9

T , .

+2

While you cannot do what you are looking for with common constraints, you can use reflection to check the type at runtime to determine if it has these properties and dynamically get its values.

Disclaimer: I am doing this from head to toe, maybe I'm a bit off track.

public static bool IsMixed(this object obj)
{
    Type type = obj.GetType();

    PropertyInfo isThisProperty = type.GetProperty("IsThis", typeof(bool));
    PropertyInfo isThatProperty = type.GetProperty("IsThat", typeof(bool));

    if (isThisProperty != null && isThatProperty != null)
    {
        bool isThis = isThisProperty.GetValue(this, null);
        bool isThat = isThatProperty.GetValue(this, null);

        return isThis && isThat;
    }
    else
    {
        throw new ArgumentException(
            "Object must have properties IsThis and IsThat.",
            "obj"
        );
    }
}
+2
source

pretty much the only way to do this is to have an interface as the basis for what you're working with:

interface iMyInterface
{

}

public static bool IsMixed<T>(this T obj) where T: iMyInterface
{
   return obj.IsThis && obj.IsThat;
} 
0
source

All Articles