-3

Can someone tell me if C# automatically initializes variables? If so, what are the default values?

10
  • 1
    No, and you can easily demonstrate this in a few lines of code. Commented May 7, 2013 at 20:23
  • 1
    read up on "automatic properties" and "value types" in c# Commented May 7, 2013 at 20:24
  • Actually it does initialize member variables of a class Commented May 7, 2013 at 20:24
  • First response in googleing your exact question Commented May 7, 2013 at 20:24
  • 1
    look at default keyword Commented May 7, 2013 at 20:24

2 Answers 2

3

When you declare something inline it will not

int Foo()
{
    int bar; //Bar is not initlized, this code will not compile
    bar =  bar + 1;
    return bar;
}

However if you declare inside a class it will have a default value equal to default(type)

class Baz
{
   int bar;

   int Foo()
   {
        bar =  bar + 1;
        return bar; //default(int) is 0 so this returns "1"
   }
}
Sign up to request clarification or add additional context in comments.

Comments

2

c# has no default value for variables if the variable scope is a method ... if the scope is at least field, the default value will be default(YourType) ... see http://msdn.microsoft.com/en-gb/library/xwth0h0d%28v=vs.80%29.aspx

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.