This project is read-only.

Generics usage in extensions methods

Topics: C# Language Design, General
Nov 24, 2015 at 11:53 AM
Edited Nov 24, 2015 at 11:57 AM
Hi all!

I encountered interesting issue within types handling in C#.

Imagine that we have 2 classes
class Class1 { }

class Class2 { }
And then we write 2 different extension methods sets
static class TestExtensions
    public static T DoSomething<T>(this T x) where T : Class1 { return x; }

static class TestExtensions2
    public static T DoSomething<T>(this T x) where T : Class2   { return x; }
No compilation errors, no warnings.
Then we try to use extension method with Class1 variable
static class Test
    static void Main()
        var c1 = new Class1();
// And here we are getting ambigous invocation compile-time error
We got "ambigous invocation" but this call is type-safe since no constraint violations. i.e. if we reveal this call to direct static method invocation then we are not able to call TestExtensions2.DoSomething() for instance of type Class1 and vice versa.

So this kind of "generics polymorphism" seems not working.

Therefore I have 2 questions:
  1. Is it compiler/language design bug or feature? So should it be fixed and where should I complain/do pull request? :)
  2. How should I rewrite my extension methods that actually should consume instance of specified type (and its inheritors) and return instance exactly of type supplied? I'm writing some fluent things.
Dec 9, 2015 at 3:10 AM
Hi, note that Roslyn has moved to Github (, so that is a better place to file this.