The answer is 10. The complete program follows. Scroll down to
read the Q&A about the program.
| using System;
class Y { public static implicit operator Y(Q q) { Console.WriteLine("converting Q to Y"); return new Y(); } public static W operator +(Y y1, Y y2) { Console.WriteLine("adding Y and Y returning W"); return new W(); } }
class Z { public static W operator +(Z z, Y y2) { Console.WriteLine("adding Z and Y returning W"); return new W(); } }
class W { public static implicit operator Y(W w) { Console.WriteLine("converting W to Y"); return new Y(); } }
class B { public static implicit operator int(B b) { Console.WriteLine("converting B to int"); return 9; } }
class X { public Y y { get { Console.WriteLine("getting y"); return new Y(); } set { Console.WriteLine("setting y"); } } }
class Q { }
class A { public Q this[int index] { get { Console.WriteLine("indexing A, returning Q"); return new Q(); } } }
class Test { public B b { get { Console.WriteLine("getting b"); return new B(); } } public X x { get { Console.WriteLine("getting x"); return new X(); } } public A a { get { Console.WriteLine("getting a"); return new A(); } } public void foo() { x.y += a[b]; } static void Main() { Test t = new Test(); t.foo(); } } |
A: A benign-looking statement with 10 hidden function calls?
Hopefully not! If they do then debugging will be a nightmare.
A: Stay away from operator overloading, indexers, properties and user-defined
type conversion operators if you don't want to end up creating a maintenance
programmer's worst nightmare.
A: At what point can you say that a feature has been misused? Each class in the
above program may have been written by a different programmer. Taken in isolation,
each class seems reasonable. But together they create a nightmare.
Unless the smallest pieces of your program are designed to be as simple as
possible, the pieces acting together will challenge the limits of human
comprehension.
A: No, not unless you think people like Albert Einstein and Professor C. A. R. Hoare
are stupid. (Read what they said about simplicity here.)
Always make simplicity a goal when you write code. Wanting simplicity does not
mean you are stupid. If you think complexity is OK, that does mean you
are not very smart!
C# Best Practice
Do not use operator overloading or indexers
|
[Back to Index]
|