What are the default value for a field in C#
Description
For class level fields we don't need to set the initial value. C# sets the initial value if the fields aren't initialized.
Default value for each type
From the output we can see that the Width is initialized to 0. The following table shows the auto-initialized value for each predefined data types:
Type | Default value |
---|---|
Reference types | null |
numeric types | 0 |
enum types | 0 |
char type | '\0' |
bool type | false |
using System;//from www. j av a2 s . c o m
class Test{
public char ch;
public bool b;
public int i;
public string str;
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
Console.WriteLine(t.ch);
Console.WriteLine(t.b);
Console.WriteLine(t.i);
Console.WriteLine(t.str);
}
}
The output:
Example
Example for C# Field default value
using System;/*w w w . j ava 2 s . co m*/
class Rectangle {
public int Width;
public int Height;
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
}
}
The output: