Reputation: 2537
Consider the following code:
public class ClassA
{
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
// Somewhere else
var obj = new ClassA
{
PropertyA = 1,
// Question:
// How do we force PropertyB to be set here without making it a parameter in the constructor?
// Ideally in compile time so that the code here would cause a compile error.
};
Motivation: This question came to me when I tried to inject dependencies by properties instead of in constructors.
Upvotes: 1
Views: 787
Reputation: 109537
Perhaps you don't realise this, but you can combine an object initialiser with a constructor.
So you can force initialisation in the constructor and still allow an object initialiser like so:
public class ClassA
{
public ClassA(int propertyB)
{
PropertyB = propertyB;
}
public int PropertyA { get; set; }
public int PropertyB { get; set; }
}
Hence:
var obj = new ClassA(2 /*Property B*/)
{
PropertyA = 1
};
However, in answer to your question: No, you can't force a property to be initialised in an object initialiser.
Upvotes: 4