Optional Parameter in C#   Leave a comment

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");


You will get the below result.


Posted October 26, 2014 by Izharuddin Shaikh in C#

Tagged with

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: