Quantcast
Channel: Type inference – Fabulous adventures in coding
Viewing all articles
Browse latest Browse all 11

An inheritance puzzle, part one

$
0
0

Once more I have returned from my ancestral homeland, after some weeks of sun, rain, storms, wind, calm, friends and family. I could certainly use another few weeks, but it is good to be back too.

Well, enough chit-chat; back to programming language design. Here’s an interesting combination of subclassing with nesting. Before trying it, what do you think this program should output?

public class A<T> 
{
  public class B : A<int> 
  {
    public void M() 
    {
      System.Console.WriteLine(typeof(T).ToString());
    }
    public class C : B { }
  }
}
class MainClass 
{
  static void Main() 
  {
    A<string>.B.C c = new A<string>.B.C();
    c.M();
  }
}

Should this say that T is int, string or something else? Or should this program not compile in the first place?

It turned out that the actual result is not what I was expecting at least. I learn something new about this language every day.

Can you predict the behaviour of the code? Can you justify it according to the specification? (The specification is really quite difficult to understand on this point, but in fact it does all make sense.)

The answer is in the next episode!


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images