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:

TypeDefault value
Reference typesnull
numeric types0
enum types0
char type'\0'
bool typefalse

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:





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor