Methods with optional parameters (parameters with default values)

by Jagadish Pulakhandam on 9/8/2011 11:55:16 AM
Rated 0 from 0 votes
Brief: Demonstrates on defining methods with optional parameters (parameters with default values) and using the named parameter notation.
Posted to: Basics of Object Oriented Programming in .NET
Add to DiggAdd to del.icio.usAdd to FURLAdd to RedditAdd to YahooAdd to BlinklistAdd to GoogleAdd to ma.gnoliaAdd to ShadowsAdd to Technorati

Demonstrates the following:
  • Define methods with optional parameters (parameters with default values)
  • Access methods with optional parameters
  • Overwrite the default values of optional parameters when calling methods
  • using named parameter notation, to provide values to specific parameters.
Follow inline comments in code.

Source Code:

01.using System;
02.using System.Collections.Generic;
03.using System.ComponentModel;
04.using System.Data;
05.using System.Drawing;
06.using System.Linq;
07.using System.Text;
08.using System.Windows.Forms;
09. 
10.namespace NamedParameters
11.{
12.    public partial class Form1 : Form
13.    {
14.        public Form1()
15.        {
16.            InitializeComponent();
17.        }
18. 
19.        private void button1_Click(object sender, EventArgs e)
20.        {
21.            //'10' gets assigned to 'a'.
22.            //'b' and 'c' will have default values (1 and 2 respectively).
23.            Add(10);   //displays '13'
24. 
25.            //'10' gets assigned to 'a'.
26.            //'20' gets assigned to 'b'.
27.            //'c' will have default value 2
28.            Add(10, 20); //displays 32
29. 
30.            //'10' gets assigned to 'a'.
31.            //'20' gets assigned to 'b'.
32.            //'30' gets assigned to 'c'.
33.            //no default values are taken in to account
34.            Add(10, 20, 30); //displays '60'
35. 
36. 
37.            //'10' gets assigned to 'a'.
38.            //'20' gets assigned to 'c' (named parameter).
39.            //'b' will have default value 1
40.            Add(10, c: 20); //displays 31
41. 
42. 
43.            //can also do this in any order (using named parameter notation)
44.            Add(a: 10, b: 20, c: 30); //displays 60
45.            Add(c: 30, a: 10, b: 20); //displays 60
46.        }
47. 
48.        private void Add(int a, int b = 1, int c = 2) //default values of b and c are 1 and 2 respectively
49.        {
50.            MessageBox.Show((a + b + c).ToString());
51.        }
52. 
53. 
54.    }
55.}


Join the .NET Code Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
0

Rated 0 from 0 votes ( login  to rate)
DotnetKicks DotnetKicksDe DotNetShoutout

Attachments / Source Code
You need to Login or Join for FREE to download the following