1

My client came up with a weird requirement that for every .ToString() call in the project code, we should do a customized operation(like adding a row in db)

I felt extension methods will be much useful for me, if it provides me overriding facility.

Any reason why Microsoft did not allow extension methods to override existing behavior of the class methods?

I heard compiler prioritizes extension methods as lower than the class method. Is there a way to modify compiler to priorities extension methods more than class methods?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Deepak Raj
  • 730
  • 2
  • 9
  • 26
  • 4
    That's a *really* bizarre requirement. I suggest you simply push back on it. (Does the client want that behaviour for every *implicit* call to ToString to, e.g. in string concatenation? What about calls to ToString within .NET framework code?) – Jon Skeet Feb 14 '13 at 07:17
  • 1
    I agree. Educate your client. That's also part of your job as a consultant. – Daniel Hilgarth Feb 14 '13 at 07:18
  • i too agree with this :).. thanks for ur comments.. – Deepak Raj Feb 14 '13 at 07:23
  • This could be a good reading for explaining to your client http://www.codinghorror.com/blog/2008/07/monkeypatching-for-humans.html – Martheen Feb 14 '13 at 08:07
  • voila! i was not aware of this ..great share.. super like.. – Deepak Raj Feb 14 '13 at 09:19

2 Answers2

7

Is there a way to modify compiler to priorities extension methods more than class methods?

No you can't.

I would quote Eric Lippert from a similar question:

The purpose of extension methods is to extend the set of methods available on a type, not to override existing methods; that's why they're called "extension methods"

From MSDN - Extension Method:

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.

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
1

Actually there is a problem with extensions itself. Because ToString() method of instance will have proirty over extension.

There is a good explanation on the Microsoft Developer Network.

In short:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            string value = "test";
            Console.WriteLine(value.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
        Console.WriteLine("End");
        Console.Read();
    }
}
public static class StaticExtensions
{
    public static string ToString(this Object obj)
    {
        if (obj == null)
            return "";
        else
            return obj.GetType().FullName + obj.ToString() ;
    }
}

will return test.

You should probably try another way. Maybe proxy object or some thing in that direction.

Rudi Visser
  • 21,350
  • 5
  • 71
  • 97
Aler Close
  • 81
  • 2