Friday, September 25, 2009

Interesting Interview Code Question

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?

A: A::DoAStuff()
B::DoBStuff()
A::DoAStuff()
B::DoBStuff()

2) Why does it work?

Op A: Operator Overloading

3) Why would I write code like this?

Mu A: Multiple Inheritance Workaround

4) Explain how it works?

A: Using operator overloading A and B to achieve the “type casting” A and B (not the same instance).

No comments:

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...