What's new in Visual C# 4.0 ? - Part 2 - Names Parameters
This is the second post of what’s new in Visual Studio C# 4.0.
At the former post we reviewed the feature of optional parameters at this post we will concentrate on Named Parameters.
Named Parameters
Lets assume you are writing the following procedure :
- public static void SaySomething(string name, string msg)
- {
- Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
- }
When you want to call it from your code you are using something like:
- static void Main(string[] args)
- {
- SaySomething("Ohad","What's up?");
- Console.ReadLine();
- }
What’s the problem ?
Although you will have intellisense while you are coding it for the reader of the code its unclear what is the first parameter and what is the second parameter.
This is where Named Parameters gets into the picture. Using named parameter the code becomes much more readable to one who haven’t wrote it.
- class Program
- {
- static void Main(string[] args)
- {
- SaySomething(name: "Ohad", msg: "What's up?");
- Console.ReadLine();
- }
- public static void SaySomething(string name, string msg)
- {
- Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
- }
- }
Named parameters are specially useful whenever you have multiple optional parameters of the same type. Without using named parameter how would the compiler know if the parameter which is being passed by line 5 is the name or the message.
- class Program
- {
- static void Main(string[] args)
- {
- SaySomething(name: "Ohad");
- Console.ReadLine();
- }
- public static void SaySomething(string name = "Tirza", string msg = "Hi There")
- {
- Console.WriteLine(string.Format("Hi {0} !\n{1}", name,msg));
- }
- }