Named and Optional Parameters in C# 4.0

Named parameters allow you to pass parameters into a function in any order and are near essential when using C#'s other new feature: optional parameters. To use a named parameter, simply specify the parameter name followed by a colon and then the value you are passing into a function. 

Here is a method  where Message1 and Message2 are required and Message3 is optional

private void Message(string Message1, string Message2, string Message3 = "Hello")      

{ }      


Above method can be called in following different ways:

     Message("R1", "R2");              

     Message(Message1:"R1",Message2:"R2");

     //Optional parameters must appear after required parameters

     Message("R1", "R2","Hello World");

     //Names parameters

     Message(Message1: "R1", Message2: "R2", Message3 :"Hello World");

Ebook Download
View all
Learn
View all