Friday, September 23, 2016

C# Puzzle: Questions on Extension Methods

Question (1):
What is the output of the following program ?



public class Program
{
    public static void Main()
    {
        var obj = new MyClass();
        obj.SayHello();
    }
}

public class MyClass
{
    public void SayHello()
    {
        System.Console.WriteLine("Hello, Original");
    }
}

public static class Ex
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension");
    }
}

Question (2):
What is the output of the following program ?



public class Program
{
    public static void Main()
    {
        var obj = new MyClass();
        obj.SayHello();
    }
}

public class MyClass
{
    
}

public static class Ex1
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension1");
    }
}

public static class Ex2
{
    public static void SayHello(this MyClass obj)
    {
        System.Console.WriteLine("Hello, Extension2");
    }
}

Answers
  1. The program will print "Hello, Original", because when the instance method and the extension method both have the same signature, the instance method will always have higher priority.
  2. The program will cause a compile-time error, because the call of "SayHello" function is ambiguous between two extension methods in classes "Ex1" and "Ex2".

No comments:

Post a Comment