Can someone tell me if C# automatically initializes variables? If so, what are the default values?
2 Answers
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"
}
}
Comments
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
defaultkeyword