Field default value
In this chapter you will learn:
Field default value
For class level fields we don't need to set the initial value. C# sets the initial value if the fields aren't initialized.
using System;/* j av a2 s .com*/
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:
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;// ja v 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:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class