is it necessary to initialize an auto property?
public string thingy { get; set; }
the reason I ask is because I have just come across a bunch of code where it was used where, the default value of null being an acceptable value.
the compiler does not complain.
as a general point, why does the compiler enforce initializations if it will default numbers to zero and object references to null anyway?
autopropeties initialize by default(T)
if you want initialize by special value you can use backing field:
private string _thingy = "value";
public string Thingy
{
get { return _thingy; }
set { _thingy = value; }
}
or set value in constructor
public class MyClass
{
public string Thingy{get;set;}
public MyClass()
{
Thingy = "value";
}
}
or set in any method
The compiler enforces initializations for local variables, not for fields or properties. C# requires that local variables be definitely assigned because use of unassigned local variables is a common source of program bugs. That's not because the unassigned variable might contain garbage -- the CLR guarantees that it will not -- but because the programmer has probably made a mistake in the code.
The compiler doesn't treat fields or properties the same way because it's impossible to do the necessary flow analysis across multiple methods that could be called in any order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With