Advertisement



< Prev
Next >



C# Constructors





In C#, a constructor is used to create an object of a class by using the new keyword, where an object is also known as an instance of a class. Each object will have its own instance variables and access to the methods of its class.

Some important features of a constructor are -






Overloading a constructor means providing multiple versions of a constructor, where each version has a different type or number of argument list.




Use of overloaded constructors



An example of overloaded constructor


//C# Example of a class with overloaded constructors i.e. different versions of a constructor 

using System;

class MathOP
{

//Constructor to add two int values
public MathOP(int a, int b)	
{
	Console.WriteLine(a+b);
}

//Constructor to add two String objects
public  MathOP(String a, String b)	
{
	Console.WriteLine(a+b);
}


//Constructor to add two float values
public MathOP(float a, float b)	
{
	Console.WriteLine(a+b);
}


//Constructor to add two char values
public MathOP(char a, char b)
{
	Console.WriteLine((char)(a+b));
}
}


class Cons
{
public static void Main(String[] ar)
{
	//Calling the constructor version which takes two int values
	MathOP ob1= new MathOP(1,2);
	
	//Calling the constructor version which takes two String values
	MathOP ob2= new MathOP("John","Denver");
	
	//Calling the constructor version which takes two float values
	MathOP ob3= new MathOP(2.2f, 2.5f);
	
	//Calling the constructor version which takes two char values
	MathOP ob4= new MathOP('a', 'x');
}
}


Output-


3
JohnDenver
4.7
U

In this program, we have created a class MathOP having multiple versions of constructors, where each version has a different type or number of argument list i.e. each constructor involved in some specialized talk of adding two integers, characters, strings or float values.




How does a compiler know which constructor to call?
Based on the type and the number of arguments used to call a constructor, a specific constructor is called. For example - if a constructor is called with int arguments, a constructor accepting int arguments is invoked and int values are passed to it.



Please share this article -





< Prev
Next >
< C# Inheritance
C# Destructors >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement