Extension methods dispatch based on static C# with Example



Extension methods dispatch based on static C# with Example

type 
The static (compile-time) type is used rather than the dynamic (run-time type) to match parameters. 
public class Base 
{ 
public virtual string GetName() 
{ 
return "Base"; 
} 
} 
public class Derived : Base 
{ 
public override string GetName() 
{ 
return "Derived"; 
} 
} 
public static class Extensions 
{ 
public static string GetNameByExtension(this Base item) 
{ 
return "Base"; 
} 
public static string GetNameByExtension(this Derived item) 
 

{ 
return "Derived"; 
} 
} 
public static class Program 
{ 
public static void Main() 
{ 
Derived derived = new Derived(); 
Base @base = derived; 
// Use the instance method "GetName" 
Console.WriteLine(derived.GetName()); // Prints "Derived" 
Console.WriteLine(@base.GetName()); // Prints "Derived" 
// Use the static extension method "GetNameByExtension" 
Console.WriteLine(derived.GetNameByExtension()); // Prints "Derived" 
Console.WriteLine(@base.GetNameByExtension()); // Prints "Base" 
} 
} 
Live Demo on .NET Fiddle 
Also the dispatch based on static type does not allow an extension method to be called on a dynamic object: 
public class Person 
{ 
public string Name { get; set; } 
} 
public static class ExtenionPerson 
{ 
public static string GetPersonName(this Person person) 
{ 
return person.Name; 
} 
} 
dynamic person = new Person { Name = "Jon" }; 
var name = person.GetPersonName(); //  RuntimeBinderException  is  thrown 

0 Comment's

Comment Form

Submit Comment