Reputation: 89
Lets say I have a class
class Car
{
string color;
bool fourDoor;
int numberOfTires;
}
And I create a new instance
Car myCar = new Car();
myCar.color = "green";
myCar.fourDoor = true;
I haven't assigned anything to numberOfTires
so how do I make it throw a compile warning/error?
Upvotes: 1
Views: 69
Reputation: 178
You can set the properties that need to initialised in the argument of the constructor. This way u can force the user to pass value during the object creation.
public class Car { public Car(string color, bool fourDoor, int numberOfTires) { this.Color = color; this.FourDoor = fourDoor; this.NumberOfTires = numberOfTires; }
public string Color { get; set; }
public bool FourDoor { get; set; }
public int NumberOfTires { get; set; }
}
Upvotes: 0
Reputation: 1063298
That isn't something supported by the compiler as it is not required to assign something to all properties. You could write an analyzer for it, but in non-trivial cases it will quickly become "halting problem" complex.
Note that if Car
was a struct
then that can be checked via a very specific syntax (only if you don't initialize the value first), but: that is so nuanced that it won't help you, and it wouldn't be good advice (and that is before we discuss the issue of mutable structs).
In your case, your best bet would be to use the constructor to declare what things you require. Then it becomes:
Car myCar = new Car(color: "green", fourDoor: true, numberOfTires: 42);
My explicit usag of parameter names is purely for visibility; it would work just as well as:
Car myCar = new Car("green", true, 42);
This would map to something like:
class Car
{
public string Color {get;}
public bool FourDoor {get;}
public int NumberOfTires {get;}
public Car(string color, bool fourDoor, int numberOfTires)
{
Color = color;
FourDoor = fourDoor;
NumberOfTires = numberOfTires;
}
}
Upvotes: 5
Reputation: 385
Jason gives a good option for your problem: https://stackoverflow.com/a/10720455/3836632
"I think that your configuration parameters should be readonly
(and arguably private
but accessible via a property). Then, set warnings to be marked as errors. Then, when you fail to initialize one of these variables, you'll get a compile-time error
The field
CalculatorConfig.param1
is never assigned to, and will always have its default value.
Now you've caught the issue at compile time."
Upvotes: 1
Reputation: 1130
For such case, you should use constructor with arguments. Take a look here: https://msdn.microsoft.com/en-us/library/k6sa6h87.aspx.
Upvotes: 4