4

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?

2
  • it will always be default(T) Commented Aug 3, 2012 at 7:58
  • The compiler enforces initializations on local variables - they never get default values. Member variables on the other hand will get default values. Commented Aug 3, 2012 at 8:18

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

Also worth reading is the answer from Eric Lippert here: stackoverflow.com/questions/8931226/…
@NoviceProgrammer thanks for posting that link. Almost everything I know about the C# compiler comes from Eric's blog or his answers on stackoverflow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.