Total number of ways to call default parameter in c#.

Default parameter is a way to pass default value to a method when less argument is passing.

this can be achieve by 4 ways.

I) method overloading
2) using [OPTIONAL] keyword
3) using param keyword(it should be the last argument)
4)assigned at the time of declaration

example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;

namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{

addition obj = new addition();
Console.WriteLine( obj.add(1));//output 2
Console.WriteLine(obj.add());//
Console.WriteLine(obj.add(3, 4));
Console.WriteLine(obj.add1(a: 1, c: 2));//
addition obj1 = new addition();
Console.WriteLine (obj1.sub(4, 1));

Console.WriteLine (obj1.sub(1));
addition obj2 = new addition();
Console.WriteLine (obj2.mul(1,2,3));
Console.WriteLine (obj2.mul(1));
}
}
}
public class addition
{
public int add(int x=0,int y=1)
{
int r=x+y;
return r;
}
//optional keyword is only use at end//
public int sub(int x,[Optional] int y)
{
int r = x – y;
return r;
}
//params keyword only use at end//
public int mul(int x,params int[] y)
{
int r = 1;
foreach(int a in y)
{
r *= a;
}
return (r * x);
}

///

///
///

///
///
///
///
public int add1(int a, int b = 0, int c = 4) { return a + b + c; }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s