Next step of programming

Just another WordPress.com weblog

Named & Optional Parameter, C# 4.0 Part 2

with one comment

In visual basic we were having optional parameter option which can help you to send only some parameter to methods and reset will take the default values. Same feature is part of C# 4.0 where you can have default values for the parameters.

Optional Parameters & Their default values

Optional Parameters & Their default values


But one more noticeable feature is “named parameter”. You might have seen in VB also that if you want to set any of the parameter no values then you have to leave all other parameters also which are defined after that variable. To sort this out you can use named parameter which specify the name of the parameter and value for it “seats:4” where seats is the parameter and 4 is the value.

Named Parameters

Named Parameters


Both of the features are shown below in sample

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParameterFeatures
{
class Program    
{
static void Main(string[] args)
{
Vehicle car = new Vehicle("V6");
Vehicle van = new Vehicle(seats:4);

Console.WriteLine("Engine : " + car.Engine);
Console.WriteLine("Seats : " + van.Seats.ToString());

Console.ReadLine();
}
}

class Vehicle    
{
public string Engine { get; set; }
public int Seats { get; set; }

public Vehicle(string engine = "V8", int seats = 5)
{
Engine = engine;
Seats = seats;
}
}
}

Written by A.Sethi

March 16, 2009 at 12:39 pm

One Response

Subscribe to comments with RSS.

  1. [...] Named & Optional Parameter, C# 4.0 Part 2 [...]


Leave a Reply