Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extensions method replaces the standard method in C#

There are ways to use extension methods with signatures of standard methods as extension (without explicit appeal to static class)? For example:

public class Foo
{
    public override string ToString()
    {
        return "Own";
    }
}

public static class ExtensionsMethods
{
    public static string ToString(this Foo foo)
    {
        return "Extensions";
    }
}

class Program
{
    static void Main()
    {
        var foo = new Foo();            
        Console.WriteLine(foo.ToString()); // "Own" will be printed
    }
}

Can I use Extensions-ToString version without explicit appeal to class ExtensionsMethods

like image 731
AndreyAkinshin Avatar asked Jan 21 '26 18:01

AndreyAkinshin


1 Answers

No, you cannot do this. An extension method is not used if a method with the same signature is available:

You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called.

See Extension Methods (C# Programming Guide) with Binding Extension Methods at Compile Time for details.

There might be inheritance or a decorator as an alternative solution for you.

like image 89
Matthias Meid Avatar answered Jan 23 '26 07:01

Matthias Meid