Work with constructor's parameters in C#
Named parameters
We can use the named parameters with constructors to initialize the fields.
using System;/*from w w w .java 2 s. c o m*/
class Rectangle {
public int Width;
public int Height;
public Rectangle(int w, int h){
Width = w;
Height = h;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(h : 6, w:5);
Console.WriteLine(r.Width);
Console.WriteLine(r.Height);
}
}
The output:
Optional parameters
Constructors can have optional parameters as well.
using System;//from w w w . j a v a2 s .com
class Rectangle {
public int Width;
public int Height;
public Rectangle(int w = 5, int h = 6){
Width = w;
Height = h;
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
Console.WriteLine(r.Width);
Console.WriteLine(r.Height);
}
}
The output: