Optional Parameters in C# 4.0 and Limitations

No.of Views2647
Bookmarked0 times
Downloads 
Votes1
By  pranay rana   On  12 Jan 2011 21:01:24
Tag : CSharp , CSharp4.0
In this article, I will explain how to use the optional parameter in C 4.0 and what are the limitations or points we have to keep mind before use these types of parameters in coding.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, I will explain how to use the optional parameter in C 4.0 and what are the limitations or points we have to keep mind before use these types of parameters in coding.

What is Optional Parameter(s) ?

In C#4.0 Optional parameter allows to create method(s) with the parameters which is having default values with it.

Syntax

Accessmodifier ReturnType NameOfMethod(Type param1, Type Pram2,....,Type Param(n-1)=DefultValue,Type Param(n)=DefultValue )
{
   //code goes here
}

Example

public void MyOptParamTest(int a, int b=10)
{
   //code goes here
}

Points To Remeber

It's very easy to implement the method with the Option Parameter(s). But one should keep in mind following points when using it

  • Optional parameter(s) must come after required parameters.
//valid
public void MyOptParamTest(int a, int b=10)
//not valid
public void MyOptParamTest(int b=10,int a ) 
  • But Parameter array always comes last i.e after Optional parameter(s).
//valid
public void MyOptParamTest(int a, int b=10, params int[] myArray) 
  • Parameter array cannot be optional parameter
//not valid
public void MyOptParamTest(int a, int b=10,
                         params int[] myArray = null)
  • Optional parameter(s) cannot be specified with ref and out keywords.
//not valid
public void MyOptParamTest(int a,ref int b=10) 
  • Optional parameter(s) can have any time but value of Optional parameter(s) can be constants i.e string,int etc. , null, Enum number, const member and the default(T) operator.
  • Optional parameter(s) - value types, you can call the parameterless constructor.
  • Optional parameter(s) - implicit conversion from the specified value to the parameter type, but this must not be a user-defined conversion.
//valid
public void MyOptParamTest(int a,decimal b=10)
//not valid -- user defined conversion
public void MyOptParamTest(int a,
                    XTypeVariable b=10)

Where to USE ?

  • Use full when coding methods where default value play good role i.e By specifying null value to option parameter(s).
            Consider case where I have method to calculate age of the person
public int CalcualteAge(DateTime birthDate,DateTime? deathDate= null)
    {
       DateTime actualEndDate = deathDate ?? DateTime.Now;
       TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
       int days = dateDifference.Days;
    }

So by the above way its makes code easy.

  • Decrease amount of overload method(s) where it's just become overloaded by no. of passing parameter

Consider same above case where I have method to calculate age of the person

///For person who is dead
    public int CalcualteAge(DateTime birthDate,DateTime deathDate)
    {
       TimeSpan dateDifference = deathDate.Subtract(birthDate);
       int days = dateDifference.Days;
    }
 
    ///For person who is alive
    public int CalcualteAge(DateTime birthDate)
    {
       DateTime actualEndDate =  DateTime.Now;
       TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
       int days = dateDifference.Days;
    } 

But if we use Optional parameter

public int CalcualteAge(DateTime birthDate,DateTime? deathDate= null)
    {
       DateTime actualEndDate = deathDate ?? DateTime.Now;
       TimeSpan dateDifference = actualEndDate.Subtract(birthDate);
       int days = dateDifference.Days;
    } 

So by the use of the optional parameter(s) we just have one method which is do the task of two method.

Summary

Optional parameter(s) makes code small,simple and easy to understand. thank you for reading.

 
Sign Up to vote for this article
 
About Author
 
pranay rana
Occupation-CEO
Company-GMind Solusion
Member Type-Expert
Location-India
Joined date-08 Jan 2011
Home Page-http://pranayamr.blogspot.com
Blog Page-http://pranayamr.blogspot.com
Hey, I am Pranay Rana, working as a Senior Software engineer in mid-size company located in ahmedabad. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 4.3 years now. For me def. of programming is : Programming is something that you do once and that get used by multiple for many years You can visit me on my blog - http://pranayamr.blogspot.com/ StackOverFlow - http://stackoverflow.com/users/314488/pranay My CV :- http://careers.stackoverflow.com/pranayamr
 
 
Other popularSectionarticles
    In this article, i will explain how to use the How to use ExpandoObject Class in .NET 4.0.The ExpandoObject class is introduced on .NET Framework 4.0 and inherited using many interfaces.
    Published Date : 16/Apr/2011
    C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects
    Published Date : 26/May/2010
    Dynamic Datatype in C# 4.0 is quit bit familiar to Var Datatype. Deference between Var and Dynamic is VAR initialized on CompileTime and Dynamic initialized On Runtime
    Published Date : 17/May/2010
    In this article I will show how to use the IObserver and IObservable Interfaces in C#. These two interfaces is work with connection to Push based approach on Reactive Framework
    Published Date : 15/Dec/2010
    Through this article, i will introduce in FCL named Tuple which can store n - number of values in it. Yes, you specify the type of each of those variables as generic parameters, and the object will create those values for you
    Published Date : 15/Nov/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top
</