Tuesday, July 28, 2009

VS2010 Beta C# 4.0 Optional parameters, named arguments A feature I was waiting for..

I was a VB 6.0 developer and I still doing some vb6.0 coding. I often use optional arguments(parameters) with vb6.0, which makes my life easy most of the times.

What is an optional argument?
Arguments must be provided when calling a method if it is not an optional parameter, but can omit arguments for optional parameters.


Public Function PurchaseOrder(ByVal vPurOrdNo As String, Optional vNotes As Variant)
End Function

on the above example PurchaseOrder function can be called in both ways as follows,

call PurchaseOrder("2010", "passing value to optional argument")
call PurchaseOrder("2010")

I was wondering why Microsoft dosn't introduce this feture in visual c# as it's provide such a richness for the language. I heard a good news, .Net 4.0 framework has this feture with named arguments.

* Each optional parameter has a default value as part of its definition
* If argument not passed for optional parameter then the default value will be used.
* Optional parameters must be declared after all the normal parameters (most right side)

Here is the above example PurchaseOrder method is C#

public class OptionalArgumentExample
static void Main(string[] args)
// Instance anExample does not send an argument for the constructor's
// optional parameter.

PurchaseOrder("2010", "passing value to optional argument");

// optional parameters needs to be defined with default values. in this
// example "notes" paramete has a default value, so the here the "notes"
//parametes is optional.
public void PurchaseOrder(string purordno, string notes= "default string")
//coding here..

What is a named argument?
Named arguments allows you to pass an argument for a parameter with the parameter's name rather than with the parameter's position in the parameter list.
C# .Net4.0
public class NameArgumentExample

static void Main(string[] args)
// Calling normal way
Console.WriteLine(CalculateInterest(5000, 10));

// passing with named arguments any order
Console.WriteLine(CalculateInterest(capitol: 5000, interestRate: 10));
Console.WriteLine(CalculateInterest(interestRate: 10, capitol: 5000));


static int CalculateInterest(int capitol, int interestRate)
return (( capitol / 100) * interestRate );


My Achievements

Member of

Blog Archive