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?
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.
See more on this question at Stackoverflow