C # initialization

do you need to initialize the auto property?

public string thingy { get; set; } 

the reason I'm asking for is because I just stumbled upon a bunch of code where it was used where the default value of null is a valid value.

the compiler does not complain.

as a general point, why does the compiler provide initialization if, by default, the numbers are zero and the references to objects are zero?

+4
source share
2 answers

The compiler performs initialization for local variables, and not for fields or properties. C # requires that local variables be definitely assigned, since the use of unassigned local variables is a common source of program errors. This is not because an unassigned variable may contain garbage - the CLR ensures that this is not so, but because the programmer probably made a mistake in the code.

The compiler does not process fields or properties in the same way, because it is impossible to perform the necessary flow analysis using several methods that could be called in any order.

+3
source

autopropeties is initialized to default(T) , if you want to initialize by a special value, you can use the support field:

 private string _thingy = "value"; public string Thingy { get { return _thingy; } set { _thingy = value; } } 

or set the value in the constructor

 public class MyClass { public string Thingy{get;set;} public MyClass() { Thingy = "value"; } } 

or install in any way

+5
source

All Articles