One commonly heard grievance about C# was how it did not support optional parameters. Well C# 4.0 not only has that, but you can also specify parameters by name.
Consider the following two examples :
public void RepeatText(string text, int count = 3)
{
while (count-- > 0)
{
Console.WriteLine(text);
}
Console.WriteLine();
}
public void RepeatDecoratedText(string text, string decoration = "Mr.", int count = 3)
{
while (count-- > 0)
{
Console.WriteLine("{0} {1}", decoration, text);
}
Console.WriteLine();
}
RepeatText has an optional parameter count with a default value of 3, while RepeatDecoratedText has two optional parameters. The MSIL generated for these methods are as follows (simplified, and not exact) :
.method public void RepeatText(string text, [opt] int32 count)
{
.param [2] = int32(3)
.method public void RepeatDecoratedText(string text, [opt] string decoration, [opt] int32 count)
{
.param [2] = string('Mr.')
.param [3] = int32(3)
[opt] is a parameter attribute that indicates that this parameter is optional and that the default value will be specified by .param entries. These methods can now be called as follows:
RepeatText("Nish");
RepeatText("Ant", 2);
The compiler generates code with the optional values filled in as needed:
RepeatText("Nish", 3); <-- 2nd param set via .param value RepeatText("Ant", 2); <-- No extra work needed You can also now pass an argument by name. This is particularly useful when you want to skip some optional args, but provide others. RepeatDecoratedText("Nish", count: 2); RepeatDecoratedText(count: 2, text: "Ant"); RepeatDecoratedText(decoration: "The super", count: 2, text: "Ant"); That gets compiled as: RepeatDecoratedText("Nish", "Mr." 2); RepeatDecoratedText("Ant", "Mr.", 2); RepeatDecoratedText("Ant", "The Super", 2); So basically, the parameters are either filled in via the named values provided or via the default optional values. Note that you can write optional value methods using attributes too. Example: public void RepeatTextDuplicate(string text, [Optional, DefaultParameterValue(3)] int count) { RepeatText(text, count); } // . . . RepeatTextDuplicate("Nish"); RepeatTextDuplicate("Nishant", 5); The MSIL generated for this method is identical to what you’d have got with the direct C# syntax (used earlier). As with dynamic types, apparently the biggest beneficiaries of these new named and optional parameter features are developers who interop with Office. Just like in VBScript you can now avoid having to provide optional arguments, and can also provide a named argument directly. For others, optional parameters will definitely help reduce the number of method overloads you need to write, and where there are methods that have more than a few optional parameters, the ability to call them by specifying named parameters will result in cleaner and more legible code. referred from voidnish
Blog Archive
-
▼
2009
(48)
-
▼
September
(29)
- Measuring Execution Time in C#
- C# Snippets: Directory Listing in C#
- C# Snippets: Saving User Preferences and Settings
- C# Snippets: To Obtain Current Application Directory
- C# Snippets: Beeping the PC Speaker in C#
- C# Snippets: Lorem Ipsum Generator
- C# Snippets: Foreach Loop Over Hashtable
- C# - Data Types and Ranges
- C# Snippets: String to byte[ ] and byte[ ] to String
- C# Snippets: List Box Data Binding
- C# Snippets: Limit Text Box Entry to Numeric Only
- Q) My LoginPage needs validate the UserId & Passwo...
- Trick: Clearing data from all TextBox Fast
- How to Create a MS-Access DataBase file by Clickin...
- Supporting Different Versions of MS-Access's Using...
- Q) What's Wrong in this? Getting "NullReferenceObj...
- How do i make MDI Parent & Child Forms in C#.NET a...
- How to write code : for every button click, should...
- How to insert a Line of data in the middle of the ...
- Visual C# Samples, Specifications, Quick Reference...
- Number to Text in console Program
- Number to Text1
- Generate Random Number22
- Generate Random Number2
- Generate Random Number1
- Named and optional parameters in C# 4.0
- Tip : Flush the KeyBoard buffer in C#
- How to make the numeric values as left alignment i...
- How to compute the numeric values of DataGridView'...
-
▼
September
(29)
My Links
- C# Snippets: 1
- C# Snippets: 2
- XMLFOX - CSHARP SAMPLES
- Q: Export your Crystal Report data to PDF
- Q: To create a Excel report wihtout using Excel object model Ex
- Q: Using C#, How to Save,Update Data to and from XML with out using the sql server database
- Q: upload excel to SQL using C#.net,VS2005
- Q: Export DataTable to Excel using c# with Formatting Styles
- Q: Crystal report in c# .Net
- Q: Import excel into Sql server 2005 Table
- Q: READ, UPDATE & DELETE XML FILE USING X-PATH
- Q: Export Data from Listview to Excel
- Q: About GridView Data To Excel C#
- Q: Simple way to convert excel sheet to sql table
- Q: How to send data from c# file(.cs) to xslt file
- Q: How to Export and import data from sqlserver to excel sheet in vb.net
- Q: Migration of data from access to excel and vice versa
- Q: How to insert the data from excel to Database in .Net?
- Q: How can we create excel sheet in c# using data grid
- Q: DateTime Value Manipulation
- Q: create an array from a txt file
- Q: HowtoOepnandReadanExcelSpreadsheetinaListViewin.NET
- Q: How to fill data to excel
- Q: Reading Image from Excel file using C# .Net
- C# / CSharp Tutorial
- stackoverflow.com/questions
- General .NET Projects
- Sample .NET Projects with source code
- CSharpArticles
- PHPManual
- phpmanual/en/install.windows
- ProtoPage
Wednesday, September 9, 2009
Named and optional parameters in C# 4.0
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment