Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# initializing

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?

like image 999
mfc Avatar asked Feb 20 '23 15:02

mfc


2 Answers

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

like image 131
burning_LEGION Avatar answered Feb 27 '23 14:02

burning_LEGION


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.

like image 37
phoog Avatar answered Feb 27 '23 14:02

phoog