CSharp - Type Creation Default Constructor

Features of a Constructor

  • Constructors are used to initialize objects.
  • The class name and the corresponding constructor's name(s) must be the same.
  • Constructors do not have any return types.

The common tasks, like initialization of all the variables inside a class, are done via constructors.

Default Constructor

There are two types of constructors:

  • parameterless constructors (default constructor) and
  • constructors with parameter(s) (parameterized constructors).

Demo

using System;

class Program/*from www  .ja  v a2 s.  co m*/
{
    public int myInt;
    public float myFloat;
    public double myDouble;
    public Program()
    {
        Console.WriteLine("I am initializing with my own choice");
        myInt = 10;
        myFloat = 0.123456F;
        myDouble = 9.8765432;
    }
}
class MainClass
{
    static void Main(string[] args)
    {
        //Comparison between user-defined and  C# provided default constructors
        Program ObDef = new Program();
        Console.WriteLine("myInt={0}", ObDef.myInt);
        Console.WriteLine("myFloat={0}", ObDef.myFloat.ToString("0.0####"));
        Console.WriteLine("myDouble={0}", ObDef.myDouble);
    }
}

Result

Related Topic