Optional Parameters and Named Parameters in C# 4.0

Last day I got an assignment to explore new features of .Net Framework 4.0. So I thought about writing a few posts with the new features. The first feature I explored was Optional Parameters and Named Parameters, as I am coming from VB background, I missed this feature in C# and yes we can resolve this using Overloading still we missed that feature. In .Net 4.0 Microsoft introduced Optional Parameters and Named Parameters in C#.

Both of these features are almost similar like in VB 6 or in VB.Net, unlike we don’t need an optional keyword.

class Program
{
    static void Main(string[] args)
    {
        //Optional Parameters
        ShowMessage("Hello World");
        //Named parameters
        ShowMessage("HelloWorld", backColor: ConsoleColor.Blue);
        //Normal Function call
        ShowMessage("Hello World", ConsoleColor.Red, ConsoleColor.Blue);

        Console.Read();
    }

    //In .Net 4.0
    static void ShowMessage(string message,
        ConsoleColor foreColor = ConsoleColor.Black,
        ConsoleColor backColor = ConsoleColor.White)
    {
        Console.ForegroundColor = foreColor;
        Console.BackgroundColor = backColor;
        Console.WriteLine(message);
        //Resetting Console colors to default.
        Console.ResetColor();
    }
}
This entry was posted in .Net, .Net 4.0, ASP.Net and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>