Home »
.Net »
C# Programs
How to call non-trailing arguments as default argument in C#?
Learn: How to call non-trailing arguments as default arguments in C#.Net, here is a program, which is calling non-trailing arguments.
As we know that, In C++ we can call only trailing argument as a default argument. But in C# we can call non-trailing argument as default argument. We can make only trailing argument as a default argument, but we can call non-trailing arguments.
To call non-trailing argument as a default argument, we need to use parameter name with colon operator.
Consider the program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class EMP
{
private string name ;
private int age ;
private int salary ;
public void setEmp(string name, int a = 18, int salary = 20000)
{
this.name = name ;
this.age = a ;
this.salary = salary ;
}
public void printEmp()
{
Console.WriteLine("\nEmployee Record: ");
Console.WriteLine("\tName : " + name );
Console.WriteLine("\tAge : " + age );
Console.WriteLine("\tSalary: " + salary );
}
}
class Program
{
static void Main()
{
EMP E1 = new EMP();
E1.setEmp("Sandy",25, salary: 48500);
E1.printEmp();
EMP E2 = new EMP();
E2.setEmp("Mark", a:33,34000);
E2.printEmp();
}
}
}
Output
Employee Record:
Name : Sandy
Age : 25
Salary: 48500
Employee Record:
Name : Mark
Age : 33
Salary: 34000
In above program, we are creating a class named EMP, it contains method setEmp() which has two optional or default argument (age,salary).
With E1 object, we are using salary parameter with colon( : ) operator to assign value. While with E2 object we are using a parameter with colon( : ) to set age of employee.
C# Basic Programs »