A Portion of Buff

Everybody else had one, so...

Eat Static

I answered a question in a C# forum the other day from someone looking to do runtime subclassing, similar to NMock.  The question went something like this:

"How do I overload the equals/not-equals operators for my dynamically-created class?"

Well, being hot shit at code generation, I immediately responded with something like this:

"It's easy - just define two static methods called 'op_Equality' and 'op_InEquality'".

Then I actually tried it.  Although it's quite possible to define and emit these methods correctly, it doesn't do you much good.  Operator overloads are resolved at compile-time, not at run-time, so for a statement like this:

bool areEqual = (foo1 == foo2);

if you have overloaded '==' and '!=' on type Foo in the usual manner (ie statically), the compiler will find the overload and emit MSIL similar to this:

ldloc.0

ldloc.1

call Foo::op_Equality(Foo, Foo)

If it doesn't find an overload, it will emit the regular comparison opcode:

ldloc.0

ldloc.1

ceq

And that's the problem.  Because operators are static, there are no virtual calls to exploit - if your type doesn't define an overload at compile-time, you don't get a chance to "add" one at run-time and let late-binding find it.  Same reason we don't mock static or non-virtual calls in NMock.

Comments

Shanley said:

Could you help me. To repeat what others have said, requires education; to challenge it, requires brains. Help me! I find sites on the topic: Airbrush tanning ri. I found only this - <a href="www.clubespanolrosario.org.ar/.../paasche-airbrush-tanning">paasche airbrush tanning</a>. Airbrush tanning, about it is approximately other to peel the tan bent airbrush art skin to begin. Airbrush tanning, bronzeado goes formed in logical and glowing. Thanks for the help :o, Shanley from Slovenia.

# March 24, 2010 7:20 PM

WyattNadia said:

Internet is developing very fast and it is becoming easy to buy <a href="http://www.essaysservice.com">custom essays</a> in the web. That is good to order everything you need online.

# February 3, 2011 4:38 PM

buy an essay said:

Yes, I agree with it! A valuable comments is immensely recommended. Not only for the blog owner, but for our self as well. Academic grades are not a big problem anymore, just because you can buy essays in  writing services that care about you.

# February 3, 2011 5:01 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)