0% found this document useful (0 votes)
209 views36 pages

Constructors in C #

Constructors in C# are used to initialize objects of a class. There are different types of constructors like default, parameterized, private, static, and copy constructors. The default constructor initializes objects without parameters, while the parameterized constructor accepts arguments to initialize member variables. Private constructors restrict object instantiation, and static constructors initialize static member variables. Copy constructors copy values from existing objects. Constructors can be overloaded based on parameter types or numbers. Constructors initialize objects whenever they are created.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views36 pages

Constructors in C #

Constructors in C# are used to initialize objects of a class. There are different types of constructors like default, parameterized, private, static, and copy constructors. The default constructor initializes objects without parameters, while the parameterized constructor accepts arguments to initialize member variables. Private constructors restrict object instantiation, and static constructors initialize static member variables. Copy constructors copy values from existing objects. Constructors can be overloaded based on parameter types or numbers. Constructors initialize objects whenever they are created.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Constructors in C-sharp

In this article I will explain the constructor concept in C# along with practical demonstration which will help

What is constructor?

 Constructor is used to initialize an object (instance) of a class.


 Constructor is a like a method without any return type.
 Constructor has same name as class name.
 Constructor follows the access scope (Can be private, protected, public, Internal and external).
 Constructor can be overloaded.

Constructors generally following types :

 Default Constructor
 Parameterized constructor
 Private Constructor
 Static Constructor
 Copy Constructor

The constructor goes out of scope after initializing objects. 

Default Constructor 

A constructor that takes no parameters is called a default constructor. 


When a class is initiated default constructor is called which provides default values to different data membe

You need not to define default constructor it is implicitly defined. 

Practical: Default Constructor 

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace default_constructor
{
class Program
{
class c1
{
int a, b;

public c1()
{
this.a = 10;
this.b = 20;
}

public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
}
}

static void Main(string[] args)
{
// Here when you create instance of the class default constructor will be called.
c1 ob1 = new c1();
ob1.display();
Console.ReadLine();
}
}
}

Note: In the above practical example if you don't create a constructor still there will be a default constructo
of the class with some legal values.

Parameterized constructor 

Constructor that accepts arguments is known as parameterized constructor. There may be situations, wher
members of different objects with different values when they are created. Parameterized constructors help

Practical: Parameterized Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace parameterized_constructor
{
class Program
{
class c1
{
int a, b;

public c1(int x, int y)
{
this.a = x;
this.b = y;
}

public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
}
}

static void Main(string[] args)
{
// Here when you create instance of the class parameterized constructor will be called.
c1 ob1 = new c1(10, 20);
ob1.display();
Console.ReadLine();
}
}
}

Private Constructor 

Private constructors are used to restrict the instantiation of object using 'new' operator.  A private construc
commonly used in classes that contain static members only. 
This type of constructors is mainly used for creating singleton object. 
If you don't want the class to be inherited we declare its constructor private. 
We can't initialize the class outside the class or the instance of class can't be created outside if its construct
We have to take help of nested class (Inner Class) or static method to initialize a class having private const

Practical: Private Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace private_constructor
{
class Program
{

class c1
{
int a, b;

// Private constructor declared here


private c1(int x, int y)
{
this.a = x;
this.b = y;
}

public static c1 create_instance()
{
return new c1(12, 20);
}

public void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static void Main(string[] args)
{
// Here the class is initiated using a static method of the class than only you can use pr
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
}

Static Constructors 

C# supports two types of constructor, a class constructor static constructor and an instance constructor (no
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize th
assignments. Non-static constructors are inline and are faster. 
Static constructors are used to initializing class static data members. 
Point to be remembered while creating static constructor: 
1. There can be only one static constructor in the class.
2. The static constructor should be without parameters.
3. It can only access the static members of the class.
4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.
Static methods can only use static data members. 

Practical: Static Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace static_eg
{

class Program
{

public class test
{
static string name;
static int age;

static test()
{
Console.WriteLine("Using static constructor to initialize static data members"
name = "John Sena";
age = 23;
}

public static void display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}

static void Main(string[] args)
{
test.display();
Console.ReadLine();
}
}
}

Copy Constructor 

If you create a new object and want to copy the values from an existing object, you use copy constructor.
This constructor takes a single argument: a reference to the object to be copied. 

Practical: Copy Constructor

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace copy_constructor
{

class Program
{

class c1
{
int a, b;

public c1(int x, int y)
{
this.a = x;
this.b = y;
}

// Copy construtor 
public c1(c1 a)
{
this.a = a.a;
this.b = a.b;
}

public void display()
{
int z = a + b;
Console.WriteLine(z);
}
}

static void Main(string[] args)
{
c1 ob1 = new c1(10, 20);
ob1.display();
// Here we are using copy constructor. Copy constructor is using the values already define
c1 ob2 = new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
}

Copy constructor sets behavior during runtime. It is shallow copying. 

I would be glad to share my knowledge and waiting for your feedback to increase my knowledgebase.

A constructor can be used, where every time an object gets created and if we want some code to be execut
to execute must be put in the constructor. The general form of a C# constructor is as follows

modifier constructor_name (parameters)


{
//constructor body
}

The modifiers can be private,public, protected or internal.The name of a constructor must be the name of t
can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as de
not return type for a constructor. 

The following class contains a constructor, which takes two arguments. 

class Complex
{
private int x;
private int y;
public Complex (int i, int j)
{
x = i;
y = j;
}
public void ShowXY ()
{
Console.WriteLine(x + "i+" + y);
}

The following code segment will display 20+i25 on the command prompt.  

Complex c1 = new Complex (20,25);


c1.ShowXY (); // Displays 20+i25

That is when we create the object of the class Complex, it automatically calls the constructor and initializes
that constructor is mainly used for initializing an object. Even it is possible to do very complicated calculatio
inside a constructor can throw exceptions also. 

If we don't provide a constructor with a class, the C# provides a default constructor with an empty body to
Remember that if we provide our own constructor, C# do not provide the default constructor.

The complete program is given below

// C# constructor example
// Author: [email protected]
using System;
class Complex
{
private int x;
private int y;
public Complex(int i, int j) // constructor with 2 arguments
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(x +"i+" + y);
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);
c1.ShowXY();
}

Constructor Overloading  

Just like member functions, constructors can also be overloaded in a class. The overloaded constructor mus
and/or type of arguments and/or order of arguments. 

The following program shows the overloaded constructors in action. 

// C# constructor overloading
// author: [email protected]
using System;
class Complex
{
public Complex(int i, int j) 
{
Console.WriteLine("constructor with 2 integer arguemets");
}
public Complex(double i, double j) 
{
Console.WriteLine("constructor with 2 double arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c1 = new Complex(20,25);// displays 'constructor with 2 integer arguments'
Complex c2 = new Complex(2.5,5.9); // displays 'constructor with 2 double arguments'
Complex c3 = new Complex(); displays 'no argument constructor'
}
}

Private Constructors

We already see that, in C#, constructors can be declared as public, private, protected or internal. When a c
is not possible other classes to derive from this class or create an instance of this class. Private constructor
contain only static members. However a class can contain both private and public constructor and objects o
not by using the private constructor.

The following is a valid program in C# 

// C# constructor both private & public


// Author: [email protected]
using System;
class Complex
{
private Complex(int i, int j) 
{
Console.WriteLine("constructor with 2 integer arguments");
}
public Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}

However the following program do not compile since it contain only private constructors 

// C# constructor only private. Will show compilation error.


// Author: [email protected]
using System;
class Complex
{
private Complex()
{
Console.WriteLine("no argument constructor"); 
}
}
class MyClient
{
public static void Main()
{
Complex c3 = new Complex();
}
}
public void Method1()
{
Console.WriteLine("Method of a non-abstract class");
}

Constructor Chaining

The entire above program shows that C# supports constructor overloading. In C#, even one constructor ca
class or in the base class of this class. This is what is known as constructor chaining.A special type of synta
follows. 

// C# constructor chaining 
// Author: [email protected]
using System;
class Complex
{
private Complex()
{
Console.Write("1"); 
}
private Complex(int x):this()
{
Console.Write("2"); 
}
public Complex(int x, int y):this(10)
{
Console.Write("3"); 
}
}
class MyClient
{
public static void Main()
{
Complex c = new Complex(10,20); // Displays 123
}

In the above program the Complex(int x, int y) invokes the Complex(int x) constructor by using a special s
invokes the Complex() constructor.

Static Constructors 

The normal constructors, which we explained till now, can be used for the initialization of both static and no
special type of constructor known as static constructor to initialize the static data members when the class
any other static member functions, static constructors can't access non-static data members directly.

The name of a static constructor must be the name of the class and even they don't have any return type.
the static constructor from the normal constructors. The static constructor can't take any arguments. That m
constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor. 

For example

// C# static constructor
// Author: [email protected]
using System;
class Complex
{
static Complex()
{
Console.WriteLine("static constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c;
Console.WriteLine("RAJESH");
c = new Complex();
}

The output of the above program is 


RAJESH
static constructor  

Note that static constructor is called when the class is loaded at the first time. However we can't predict the
constructor execution. They are called before an instance of the class is created, before a static member is
the derived class is called. 

Like non-static constructors, static constructors can't be chained with each other or with other non-static co
base class is not inherited to the derived class. 

Constructors & Inheritance 

Both static and non-static constructors are not inherited to a derived class from a base class. However, a de
a base class non-static constructor by using a special function base(). It is possible to invoke both default a
class from the derived class. If we don't call the base class constructor explicitly, the derived class construc
base class implicitly when an object of the derived class is created. This is shown in the program given belo

// C# Implicit call of base class default constructor


// Author: [email protected] 
using System; 
class Base
{
public Base()
{
Console.WriteLine("base constructor");
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();//Displays 'base constructor'
}

We can also call a base class constructor explicitly by using base() as shown below.  

// C# Implicit call of base class default constructor 


// Author: [email protected] 
using System; 
class Base
{
public Base()
{
Console.WriteLine("BASE 1");
}
public Base(int x)
{
Console.WriteLine("BASE 2");
}
}
class Derived : Base
{
public Derived():base(10)
{
Console.WriteLine("DERIVED CLASS");
}
}
class MyClient
{
public static void Main()
{
Derived d1 = new Derived();//Displays 'base constructor'
}
}

This program outputs


BASE2
DERIVED CLASS  

The base() can be used for chaining constructors in a inheritance hierarchy.

Destructors 

The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied b
implements the statements to be executed during the garbage collection process. A destructor is a function
class but starting with the character ~.

Example: 

class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}

Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with
error.Also destructor will come in only one form, without any arguments. There is no parameterized destruc

Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbag
the active part of the program. Execution of destructor may occur at any time after the instance or object b

In C# all classes are implicitly derived from the super base class object. The object class contains one spec
can override. The Garbage Collection mechanism in .NET will call this method prior to the garbage collection
when we provide a destructor in a class, during the compilation time, the compiler automatically generates
destructor and overridden Finalize() method can't co-exist in a class. The following code will generate a com
program 

class Complex 
{
~Complex()
{
}
protected override void Finaliz()
{
}
}

First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, an
every developer should keep in mind while working with constructors, destructors, and finalizers and class h

 Rule #1: Contrsuctors are called in descending order


 Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing
 Rule #3: Destructors are called in ascending order
 Rule #4: Finalizers are a feature of GC-managed objects only
 Rule #5: You cannot determine when finalizers would be called
 Rule #6: MC++ differs between destructors and finalizers
 Rule #7: In MC++ and classic C++, you can determine when destructors are called
 Rule #8: In MC++, destructors and finalizers are not called together
 Rule #9: Beware of virtual functions in constructors

Rule #1: Constructors are called in descending order


Rule #1: Constructors are called in descending order; starting from the root class and stepping dow
object that you need to instantiate. Applies to C#, MC++, and ANSI C++.

Let's consider a simple class hierarchy like this:

class BaseClass

    public BaseClass()

    {

        Console.WriteLine("ctor of BaseClass");

    }

class DerivedClass : BaseClass

{
    public DerivedClass()

    {

        Console.WriteLine("ctor of DerivedClass");

    }

class ChildClass : DerivedClass

    public ChildClass()

    {

        Console.WriteLine("ctor of ChildClass");

    }

ChildClass inherits from DerivedClass, and DerivedClass, in turn, inherits from BaseClass.

When we create a new instance of ChildClass using a simple line like this:

static void Main()
{
    ChildClass cls = new ChildClass();
}

The code outputs the following results:

ctor of BaseClass ctor of DerivedClass ctor of ChildClass

Rule #2: In C# lexicology, a destructor and a finaliz


thing
Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing; the function calle
the memory (i.e. GC-collected). Applies to C# only.

Let's consider the same class hierarchy but with destructors:

class BaseClass
{

    public ~BaseClass()

    {

        Console.WriteLine("dtor of BaseClass");

    }

class DerivedClass : BaseClass

    public ~DerivedClass()

    {

        Console.WriteLine("dtor of DerivedClass");

    }

class ChildClass : DerivedClass

    public ~ChildClass()

    {

        Console.WriteLine("dtor of ChildClass");

    }

When you define a class destructor with that C++-alike syntax (preceding the function name with a ~) the
with an override of the virtual Object.Finalize() function. That is, before the object is removed (i.e. GC-coll
destructor) is called first. This finalizer first executes your code. After that it calls the finalizer of the base
our assembly, we would see that our destructor in the ChildClass (so other classes) has been replaced with

protected virtual void Finalize()
{
    try
    {
        Console.WriteLine("dtor of ChildClass");
    }
    finally
    {
        base.Finalize();
    }
}

Rule #3: Destructors are called in ascending order


Rule #3: Destructors are called in ascending order, starting from the leaf object that you need to inst
reach the very first base class of your object. In reverse of constructors calling order. Applies to C#, MC++

Now, instantiate your class:

static void Main()
{
    ChildClass cls = new ChildClass();
    // 'cls' is removed from memory here
}

the code should outputs the following results:

dtor of ChildClass dtor of DerivedClass dtor of BaseClass

Rule #4: Finalizers are a feature of GC-managed objec


Rule #4: Finalizers are a feature of GC managed objects (i.e. managed classes). 
removes the object from the memory (i.e. frees memory associated with).

Now, try to create a simple structure with a destructor:

struct MyStruct
{
    ~MyStruct()
    {
        Console.WriteLine("dtor of MyStruct");
    }
}

The code won't compile. That's because that GC doesn't handle structures.

Rule #5: You can't determine when finalizers would b


That's because you don't know when the next garbage collection would occur, even if you perform
System.GC.Collect() function) you won't know exactly when memory would be released. In addition, GC a
it puts them in a special GC queue called freachable (pronounced ef-reachable, F stands for Finalize) queue
Rule #6: MC++ differs between destructors and finali
Rule #6: MC++ differs between destructors and finalizers. That is, finalizers are called by GC, and
delete the object.

Let's consider the same example but in MC++:

ref class DerivedClass : BaseClass

public:

          DerivedClass()

          {

                   Console::WriteLine("ctor of DerivedClass");

          }

          ~DerivedClass()

         {

                   Console::WriteLine("dtor of DerivedClass");

                   GC::ReRegisterForFinalize(this);

          }

};

ref class ChildClass : DerivedClass

public:

          ChildClass()

          {

                   Console::WriteLine("ctor of ChildClass");

          }
          }

          virtual void Foo() override

          {

                   cout << "Foo() of CChildClass" << endl;

          }

};

Now, run the code. It should outputs:

Foo() of BaseClass
In classic C++, the overload of the function of the class being constructed is called unlike C# and MC++ (.N

Introduction

The constructor plays significant role in the nay kind of programming language. Here I
explained the types of constructor and its limitation with suitable examples. Let us see the
constructor.

Constructors:

The constructor is a special method to the class and struts. This constructor is used to
initialize the types and objects. The complier consider as constructor when the constructor
have the same name as class name. Every class has the default constructor in the class
(default constructor). Which can be called as implicit constructor. This can be used to define
the default values the data types when there are not defined.

The user can use the default constructor for explicitly to create the instance of the classes.
The constructor access modifier is public then it will be executed when the object is
instantiated. The private constructor cannot be declaring. When object instantiate the
outside class then it will throw an error like protection level. The internal also can be defined
access modifier to the class constructor that will support up to that current assembly.

Limitations:

 The constructor should have the same as the class or struct name.
 It cannot return any values to the calling program or function.
 It static constructor cannot have any parameters.
 It should have public or internal access modifiers. It can be declared as private but
no use of it. When we instantiate the object it must throw compilation error like
inaccessible due to protection level.
 It can be used to capture the parameters and initialize the values rather than do the
complex logics.

Constructor: 

The simple constructor can be used to instantiate the object and define the data type
values.

The syntax of the constructor is the following

access-modifier Class_Name(data type Parameter1,data type Parameter 2, [Classes Obj])


{
//Code here
}

using System;
public class SimpCons
{
    private int a;
    private int b;
    public SimpCons(int x, int y)
    {
        a = x;
        b = y;
        Display();
    }
    public void Display()
    {
        Console.WriteLine("The value of a is " + a);
        Console.WriteLine("The value of b is " + b);
    }
}
class SimpleConstructor
{
    public static void Main()
    {
        SimpCons oSimpCons = new SimpCons(5, 5);
    }
}

In the above code, the constructor is used to initialize the values to the variables.

The constructor can be called the user defined the method in the both base and inherited
class. Suppose I have not used the constructor then it will use the implicit constructor to
initialize the values for the variables.

Overload Constructor

The constructor can be overloaded. As you know the constructor should be same as class
name. But it can be overloaded just like method overloading. The same polymorphism
concept can be applicable for the constructor. The same method name with different
arguments.

Overload Constructor with different data types

The constructor can be overloaded with the same name of the constructor with different
signature. The compiler only considers the signature type of the constructor. The arguments
may be like int, string, char, float, double, etc..,

using System;
class OverCons
{
    public OverCons()
    {
        Console.WriteLine("Hi! Welcome to Overload Constructor");
        Console.WriteLine("-----------------------------------");
    }
    public OverCons(int a, int b)
    {
        Console.WriteLine("The addition of " + a + " and " + b + " is " + (a + b));
    }
    public OverCons(string str1, string str2)
    {
        Console.WriteLine("Your full name is " + (str1 + str2));
    }
}
class ConstuctorOverload
{
    public static void Main(string[] args)
    {
        OverCons oOverCons = new OverCons();
        OverCons oOverCons1 = new OverCons(90, 10);
        OverCons oOverCons2 = new OverCons("Senthil", "kumar");
    }
}

This example shows there are three overloaded constructors. One is default constructor,
second one is it accepts two integer values. Final constructor accepts the string. It can be
any different combination of data types of parameter to the functions. It will not allow the
constructor with the same signature types with different variable name. Because the
compiler identifies the constructor based on the type of signature matches.

Overload Constructor with different class objects

When overload the constructors it accepts the different types of class objects. It can be
overloaded with the objects.

using System;
using System.Collections;
using System.Text;

class ObjOver
{
    public ObjOver(ArrayList oArrayList)
    {
        Console.WriteLine("Constructor - ArrayList");
        Console.WriteLine("-----------------------");
        for (int i = 0; i < oArrayList.Count; i++)
        {
            Console.WriteLine(oArrayList[i].ToString());
        }
    }
    public ObjOver(Stack oStack)
    {
        Console.WriteLine("Constructor - Stack");
        Console.WriteLine("-------------------");
        foreach (string str in oStack)
        {
            Console.WriteLine(str);
        }
    }
    public ObjOver(StringBuilder oSB)
    {
        Console.WriteLine("Constructor - StringBuilder");
        Console.WriteLine("---------------------------");
        Console.WriteLine(oSB.ToString());
    }

class ObjOverCons
{
    public static void Main(string[] args)
    {
        ArrayList oArrayList = new ArrayList();
        for (int i = 0; i < 10; i++)
        {
            oArrayList.Add(i);
        }
        Stack oStack = new Stack();
        oStack.Push("Senthil");
        oStack.Push("Kumar");
        StringBuilder oSB = new StringBuilder();
        oSB.Append("Welcome To Object Overload Constructor");
        oSB.Append(Environment.NewLine);
        oSB.Append("Sample programs developed by Erode Senthilkumar");
        ObjOver oObjOver1 = new ObjOver(oArrayList);
        ObjOver oObjOver2 = new ObjOver(oStack);
        ObjOver oObjOver3 = new ObjOver(oSB);
    }
}

Here the constructor has overloaded with the class objects. 

Private Constructor

The private constructor is a special method in the class. It can be only defined when the
class has only the static members.
using System;
public class StaticBase
{
    private StaticBase()
    {
        Console.WriteLine("Hi");
    }
    public static void Display()
    {
        Console.WriteLine("Display() method");
    }
}

class PrivateStatic
{
    public static void Main(string[] args)
    {
        StaticBase.Display();
    }
}

Here the below code cannot be executed. Here inherited class "DeriveCons" when try to
access the properties of the "BaseCons" then the constructor method is defined as private
access modifier. So it will throw exception like due to protection level.

using System; 

public class BaseCons
{
    private BaseCons()
    {
        Console.WriteLine("BaseCons Constructor");
    }
}
public class DeriveCons : BaseCons
{
    public DeriveCons()
    {
        Console.WriteLine("DeriveCons - Constructor");
    }
}
class PrivateCons
{
    public static void Main(string[] args)
    {
        DeriveCons oDeriveCons = new DeriveCons();
    }
}

Static Constructor:

Used for initializing only the static members of the class. These will be invoked for the very
first time the class is being loaded on the memory. They cannot accept any arguments.
Static Constructors cannot have any access modifiers.

using System;
class BaseStatic
{
    public static int i;
    static BaseStatic()
    {
        i = 100;
        Console.WriteLine("BaseStatic Constructor");
        Console.WriteLine("i value is " + i);
    }
}
class StaticCons
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Static Constructor");
        Console.WriteLine("------------------");
        BaseStatic oBaseStatic = new BaseStatic();
    }
}

In the above example, the static constructor will allow us to initialize the values for that
static variable. It will not allow to use any other type variable.

The below will throw an error. Because I have tried to initialize the non static variable.

using System;
class BaseClass
{
    public static int i;
    public int a = 0;
    static BaseClass()
    {
        i = 10;
        a = 15;
    }
    public void Print()
    {
        Console.WriteLine("The value of i is " + i);
        Console.WriteLine("The value of a is " + a);
    }
}
class StaticCons1
{
    public static void Main(string[] args)
    {
        BaseClass oBaseClass = new BaseClass();
        oBaseClass.Print();
    }
}
Behavior of the Constructor in the Inheritance

As you know the constructor can call the method of the class. In the below mentioned code
there are two classes. One is base class and another one is Derived class. The derived class
inherited from the base class. In the main program we have instantiated the Derived class.
The Base class has the virtual method name called Display. It has overridden in the Derived
Class. If I instantiate the Derived class then which constructor will call first?

using System;
public class BaseClass
{
    public string _ClassState;
    public BaseClass()
    {
        _ClassState = "Base Class";
        Console.WriteLine(_ClassState);
        Display();
    }
    public virtual void Display()
    {
        Console.WriteLine("Base Class - Display()");
    }
}
class DerivedClass : BaseClass
{
    public DerivedClass()
    {
        _ClassState = "Derived Class";
        Console.WriteLine(_ClassState);
    }
    public override void Display()
    {
        Console.WriteLine("Derived Class - Display()");
    }
}
class InherVirtualCons
{
    public static void Main(string[] args)
    {
        DerivedClass oDerivedClass = new DerivedClass();
    }
}

Yes! You are right!! The base class constructor will call first. Again I have called the method
name in the Display. Actually I was expecting the base class Display method call first. But
without call the Derived Class constructor it has called the Derived class Display method. In
this scenario it considers only the current derived object method.

Exception Handling in the Constructors

The constructor will allow handling the exception. Before that we no need to write the more
complex logics in the constructors. It has to be used to initialize the data types and create
the object for the built in classes.

using System;
class ConsExcep
{
    public ConsExcep(int numer, int dinom)
    {
        try
        {
            int Result = numer / dinom;
            Console.WriteLine("Result is:" + Result);
        }
        catch (Exception oEx)
        {
            Console.WriteLine("Error :" + oEx.Message);
        }
    }
}
class ExcepConstructor
{
    public static void Main(string[] arsg)
    {
        ConsExcep oConsExcep = new ConsExcep(5, 0);
    }
}

Here it handles the divide by zero exception.

Constructor in Partial Class

As we know this partial class is the new feature from C# 2.0 onwards. The same class name
can be divided into multiple classes with the same class name and different class file name
along with partial keyword.

Here a class can have the constructor in the different file name. As we know while
compilation the compiler will build the same class name in the different file as single code
unit. 

using System;
public partial class PartialClass
{
     public PartialClass()
    {
        Console.WriteLine("PartialClass Constructor");
    }
    public void Display()
    {
        Console.WriteLine("PartialClass - Display()");
    }
}
public partial class PartialClass
{
    /*
    public PartialClass()
    {
    Console.WriteLine("PartialClass Constructor1");
    }
    */
    public PartialClass(string strName)
    {
        Console.WriteLine("Name: " + strName);
    }
    public void Print()
    {
        Console.WriteLine("PartialClass - Print()");
    }
}
class PartialCons
{
    public static void Main(string[] args)
    {
        PartialClass oPartialClass = new PartialClass();
        oPartialClass.Display();
        oPartialClass.Print();
        PartialClass oPartialClass1 = new PartialClass("Erode Senthilkumar");
    }
}

Here the example shows the same default signature cannot have more than once in the
every class. Because it will became ambiguity method while compiler compile these files into
the single unit. But we can load the constructor in the different signatures in the every
partial class.

Constructors in Struct

The struct can have the constructors. But it differs from the classes. The struct is value
type. It will be stored on the stack. We have seen that class can have the default
constructor explicitly. But here stack will not allow writing the default constructor. It should
contain the parameter. But we can overload the constructor in the struct. Every struct has
the default implicit constructor. It will get execute internally to initialize the default value to
the variables. . But we cannot have the default constructor with out any parameter in the
struct like the following.

struct Employee
{
    public Employee()
    {
        Console.WriteLine("Default Constructor in struct");
    }
}

The struct should contain the constructor with the parameters like the following.

using System;
struct structstudent
{
    private string _Sname;
    private string _Class;
    private string _Age;
    public structstudent(string sname, string sclass, string sage)
    {
        _Sname = sname;
        _Class = sclass;
        _Age = sage;
    }
    public void PrintReport()
    {
        Console.WriteLine("Student Report");
        Console.WriteLine("--------------");
        Console.WriteLine("Student Name: " + _Sname);
        Console.WriteLine("Student Class: " + _Class);
        Console.WriteLine("Student Age: " + _Age);
    }
}
class StructCons
{
    public static void Main(string[] args)
    {
        structstudent oSD = new structstudent("Rama", "1st Std", "6");
        oSD.PrintReport();
    }
}

In the above struct is a valid one

You might also like