Is access to generic extension methods always the least specific?

  • There is a set of classes that I do not own - I cannot change them.
  • I would like to add an identification parameter for each of them, using the existing field in each class in which there is.
  • So, I created a set of extension methods to extract this field from each class with a default for any class that does not have a specific implementation.

This works great when directly accessing the new extension method (the first three entries in the example below), but when instances are first passed to the general method, then the selected extension method is always the object for the object (second three entries).

Am I doing something wrong, or is this a limitation of the C # compiler?

public class Call { public string Number { get; set; } } public class Message { public string Address { get; set; } } public class Unknown { } public static class Extensions { public static string ID(this object item) { return "Unknown"; } public static string ID(this Call item) { return item.Number; } public static string ID(this Message item) { return item.Address; } } internal class Program { private static void Main() { var call = new Call { Number = "555-1212" }; var msg = new Message { Address = " you@email.com " }; var other = new Unknown(); // These work just as I would expect // - printing out Number, Address, or the default System.Console.WriteLine("Call = {0}", call.ID()); System.Console.WriteLine("Message = {0}", msg.ID()); System.Console.WriteLine("Unknown = {0}", other.ID()); System.Console.WriteLine(); // These all print out "Unknown" System.Console.WriteLine("Call = {0}", GetID(call)); System.Console.WriteLine("Message = {0}", GetID(msg)); System.Console.WriteLine("Unknown = {0}", GetID(other)); } public static string GetID<T>(T item) { return item.ID(); } } 
+4
source share
1 answer

Overload resolution is performed at compile time. The compiler knows nothing about T , so the only applicable overload is:

 public static string ID(this object item) { return "Unknown"; } 

If you want to efficiently handle overload resolution at run time, and if you use C # 4, you may need to use dynamic - which, unfortunately, does not support extension methods directly:

 public static string GetID(dynamic item) { return Extensions.ID(item); } 
+5
source

Source: https://habr.com/ru/post/1433888/


All Articles