Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Generic extension method type restriction should be evaluated by the compiler.

$
0
0

So I bring some example where I encountered this problem:

I have some classes:

public abstract class HtmlElement { /* ... */ }
public abstract class UIElement : HtmlElement { /* ... */ }
public abstract class ButtonBase : UIElement { /* ... */ }
public class LinkButton : ButtonBase { /* ... */ }
public class ActionButton : ButtonBase { /* ... */ }

And I have some extension methods:

  public static class HtmlElementExtensions
  {
    public static T Id<T>(this T item, string id) where T : HtmlElement
    {
      /* set the id */
      return item;
    }
  }
  public static class ButtonBaseExtensions
  {
    public static T Id<T>(this T item, string id) where T : ButtonBase
    {
      /* set the id and do some button specific stuff*/
      return item;
    }
  }

All extension methods in one namespacce (can't separete them).

When I try to call the Id method on a LinkButton like this:

LinkButton lb = new LinkButton().Id("asd");

The compiler says it's ambigouos call. I understand why, but if the compiler watch the restrictions it could bind that call to the LinkButtonExtensionMethods.Id.

Just like non-generic extension methods:

  public class BaseClass { /*...*/ }
  public class InheritedClass : BaseClass { /*...*/ }

  public static class BaseClassExtensions
  {
    public static void SomeMethod(this BaseClass item, string someParameter)
    {
      Console.WriteLine(string.Format("BaseClassExtensions.SomeMethod called wtih parameter: {0}", someParameter));
    }
  }

  public static class InheritedClassExtensions
  {
    public static void SomeMethod(this InheritedClass item, string someParameter)
    {
      Console.WriteLine(string.Format("InheritedClassExtensions.SomeMethod called wtih parameter: {0}", someParameter));
    }
  }

And  if I instantiate these:

BaseClass bc = new BaseClass();
InheritedClass ic = new InheritedClass();
BaseClass ic_as_bc = new InheritedClass();

bc.SomeMethod("bc");
ic.SomeMethod("ic");
ic_as_bc.SomeMethod("ic_as_bc");

I got this output (without any error or warning):

BaseClassExtensions.SomeMethod called wtih parameter: bc
InheritedClassExtensions.SomeMethod called wtih parameter: ic
BaseClassExtensions.SomeMethod called wtih parameter: ic_as_bc

Thanks for reading,

Péter



Viewing all articles
Browse latest Browse all 1710

Trending Articles