Optional Parameter in C#

Optional parameter is one of the good feature of C# language, this feature allow developer to write the code with default of parameters in case user not supplying input.

Lets take an example to understand how it works. Here in the example I have created a class called MyClass and constructor with two parameters FirstName and LastName.
Where LastName is optional.

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

namespace ConsoleApplication1
{
    class MyClass
    {
        public string FirstName { get; private set; }
        public string LastName { get; private set; }

        public MyClass(string firstName, string lastName = "") {
            FirstName = firstName;
            LastName = lastName;
        }

        public string SayHello(string name) {
            return "Hello there, " + name;
        }

        public string SayHello(MyClass objMyClass){
            return SayHello(objMyClass.FirstName + " " + objMyClass.LastName);
        }
    }
}

Note*: For first name and last name, I have added the private keyword against the set accessor because I don’t want to allow it to be set from outside the class.
This also another way to make a property readonly from out side the class but read / write from same class.

Lets test the above optional parameter example using below code.

MyClass objWhiteX = new MyClass("White", "X");
MyClass objWhite = new MyClass("White");

Console.WriteLine(objWhite.SayHello(objWhiteX));
Console.WriteLine(objWhite.SayHello(objWhite));

You will get the below result.
Optional

Advertisements

#optional-parameter-in-c