Parameters of constructors
In this chapter you will learn:
Named parameters
We can use the named parameters with constructors to initialize the fields.
using System;// j a va 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 ja va 2s.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:
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class