What is parameterized constructor and advantages of parameterized constructor in C# and VB.Net

Last Reply on Mar 03, 2017 03:53 AM By dharmendr

Posted on Mar 03, 2017 03:08 AM

what are the Advantages of parameterized constructor?

You are viewing reply posted by: dharmendr on Mar 03, 2017 03:53 AM.
Posted on Mar 03, 2017 03:53 AM Modified on on Mar 03, 2017 04:49 AM

Hi divyasha,

  • A constructor with at least one parameter is called a parameterized constructor.
  • A Class or Struct can have multiple parameterized constructors as long as they have different method signature. They follow the same concept of method overloading.
  • Compiler provides Default Constructors only if there is no constructor (Default or Parameterized) defined in a class.
  • Parameterized Constructors can exist even without the existence of Default Constructors.
  • The advantage of a parameterized constructor is that you can initialize each instance of the class to different values.

Example:

C#

using System;
namespace Constructor
{
    class parameterizedconstrctor
    {
      public  int a, b;
      // declaring Paremetrized Constructor with ing x,y parameter
      public parameterizedconstrctor(int x, int y)  
      {
          a = x;
          b = y;
      }
   }

    class MainClass
    {
        static void Main()
        {
            // Creating object of Parameterized Constructor and ing values 
            parameterizedconstrctor pc = new parameterizedconstrctor(100, 175);   
            Console.WriteLine("-----------parameterized constructor example---------------");
            Console.WriteLine("\t");
            Console.WriteLine("value of a = " + pc.a );
            Console.WriteLine("value of b = " + pc.b);
            Console.Read();
        }
    }
}

VB.Net

Namespace Constructor
	Class parameterizedconstrctor
		Public a As Integer, b As Integer
		' declaring Paremetrized Constructor with ing x,y parameter
		Public Sub New(x As Integer, y As Integer)
			a = x
			b = y
		End Sub
	End Class

	Class MainClass
		Private Shared Sub Main()
			' Creating object of Parameterized Constructor and ing values
			Dim pc As New parameterizedconstrctor(100, 175)
			Console.WriteLine("-----------parameterized constructor example---------------")
			Console.WriteLine(vbTab)
			Console.WriteLine("value of a = " + pc.a)
			Console.WriteLine("value of b = " + pc.b)
			Console.Read()
		End Sub
	End Class
End Namespace

For more details refer the below link.

https://msdn.microsoft.com/en-us/library/ms173115.aspx