CSharp - Write program to use constructor to initialize variable


Create a class two different constructors.

The parameterless constructor is always initializing the instance variable i with the value 5.

The parameterized constructor can initialize the instance variable with any integer value that we supply.


In this example, we use a different constructor to create different objects that are initialized with different values.


using System;
class ClassA//from  ww  w .ja  va 2s  .c o m
    public int i;
    public ClassA()
        this.i = 5;
    public ClassA(int i)
        this.i = i;

class ClassEx4
    static void Main(string[] args)
        //A Simple class with 2  different constructor
        ClassA obA = new ClassA();
        ClassA obB = new ClassA(75);
        Console.WriteLine("obA.i =" + obA.i);
        Console.WriteLine("obB.i =" + obB.i);


Related Example