0

Why does C# object initializer has this behavior?

public class ChuckNorris
{
    public string Impact { get; set; }
}

public class Burnination
{
    public string Impact { get; set; }

    public ChuckNorris GetChuck()
    {
        var chuckNorris = new ChuckNorris
        {
            Impact = Impact // <- Why does the right hand "Impact" property here automatically refers to "Burnination.Impact" and not "chuckNorris.Impact"
        };

        return chuckNorris;
    }
}

Like the comment in the code above says. Why is that the right hand Impact property is pointing to Burnination.Impact and not the Impact property of the ChuckNorris class. How is this assumption being made that I (the developer) am referring to the Impact property of the underlying class?

1
  • I suppose because this.Impact is implied where this is Burnination and you will not initialize a property by itself which is uninitialized. Commented May 10, 2015 at 15:24

3 Answers 3

6

Basically, the expression on the RHS of the = is resolved and evaluated as it would be in any other context. So you could have:

ChuckNorris chuck1 = new ChuckNorris { Impact = "foo" };
ChuckNorris chuck2 = new ChuckNorris { Impact = chuck1.Impact };

It's only the identifiers on the left hand side of the assignment which are implicitly to do with the object being created.

Sign up to request clarification or add additional context in comments.

Comments

2

The scope belongs to class Burnination, hence implicit reference to "this".

Comments

1

The others already responded to you, but note that:

public class ChuckNorris
{
    public string Kick { get; set; }
    public string Punch { get; set; }
}

var cn = new ChuckNorris
{
    Kick = "Dead",
    Punch = Kick
};

This doesn't compile

in an assignment in an object initializer you can't reference the fields/properties/methods of the object you are creating.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.