My colleague sent me an interesting interview code question and it's pretty fun.
using System;
namespace SomeNamespaceName {
class A {
public void DoAStuff( ) { Console.WriteLine( "A::DoAStuff()" ); }
}
class B {
public void DoBStuff( ) { Console.WriteLine( "B::DoBStuff()" ); }
}
class C {
A _innerA = new A();
B _innerB = new B( );
public static implicit operator A (C c ) {
return c._innerA;
}
public static implicit operator B( C c ) {
return c._innerB;
}
public void DoAStuff( ) { ( ( A )this ).DoAStuff( ); }
public void DoBStuff( ) { ( ( B )this ).DoBStuff( ); }
}
class Program {
static void PassA( A a ) { a.DoAStuff( ); }
static void PassB( B b ) { b.DoBStuff( ); }
static void Main( string[ ] args ) {
C c = new C( );
PassA( c );
PassB( c );
c.DoAStuff( );
c.DoBStuff( );
}
}
}
Question:
1) What does the code print out?
B::DoBStuff()
A::DoAStuff()
B::DoBStuff()
2) Why does it work?
Op A: Operator Overloading
3) Why would I write code like this?
4) Explain how it works?
No comments:
Post a Comment