Code Trivia #5

A quick one inspired by real life broken code. What’s wrong in this piece of code?

class Planet
{
    public Planet()
    {
        this.Initialize();
    }

    public Planet(string name) : this()
    {
        this.Name = name;
    }

    private string name = "Unspecified";

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    private void Initialize()
    {
        Console.Write("Planet {0} initialized.", this.Name);
    }
}
Advertisements

5 thoughts on “Code Trivia #5”

    1. idd, it prints ‘Planet Unspecified initialized’ when calling constructor with name param. This is because the base ctor is called first.

  1. Yep, it prints exactly that. The original author did not take in consideration that a constructor initializer is invoked before the constructor body of the constructor that specifies the initializer.

  2. The problem is even worse when it comes to calling virtual methods, because the specialized version is called, not the base one:

    class Base
    {
    public Object SomeObject { get; set; }

    public Base()
    {
    this.Initialize();
    }

    public virtual void Initialize()
    {
    this.SomeObject = “A string”;
    }
    }

    class Derived : Base
    {
    public override void Initialize()
    {
    String s = this.SomeObject.ToString();
    }
    }

  3. Yes it’s prints Planet Unspecified initialized….

    Joao, I could not find another way to contact you so I am posting this here…

    Your blog (https://exceptionalcode.wordpress.com/) has been selected to be included into Developer IT’s search engine (http://www.developerit.com). We manually selected each and every site that gets included in our database in order to assure the quality of the articles we link to and your blog qualifies fully.

    With an Alexa Rank in the top 25,000 (http://www.alexa.com/siteinfo/http://www.developerit.com), Developer IT can bring a lot of traffic to your web site. The site is still beta, and we are planning a lot new features and a brand new design in the next months, so we need good blogs to build a usefull and powerfull search engine.

    Please respond to this e-mail within 5 business days if you do not want to be included in our database. Do not hesitate to reply or go to http://www.developerit.com/en/contact-developer-it if you have questions or comments too.

    Sincerly,

    Developer IT’s staff
    http://www.developerit.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s