Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension method restricted to objects containing specific properties

Tags:

c#

.net

generics

Is there any way to create an extension method whose parameter's only constraint is having specifically-named properties. e.g.:

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

I tried to declare the obj as dynamic but it's not allowed.

like image 800
user759141 Avatar asked Apr 20 '26 11:04

user759141


1 Answers

This feature is often called "duck typing". (Because when you call foo.Quack() all you care about is that it quacks like a duck.) Non-dynamic duck typing is not a feature of C#, sorry!

If you really have no type information about 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 interface or some such thing that describes the types at compile time.

like image 95
Eric Lippert Avatar answered Apr 22 '26 23:04

Eric Lippert