Home » .Net

C# program for Default Arguments

C#.Net Default Arguments: What are the default arguments in C#.Net? Demonstrate the concept of Default Arguments in C# by an Example.

C#.Net has the concept of Default Arguments, which are also known as Optional Arguments in C#.

Understand the concept of Default Arguments by these points:

  1. Every default argument contains a default value within the function definition.
  2. If we do not pass any argument for default argument then, it uses default value.
  3. Given default value for default argument must be a constant.
  4. Default argument cannot be used for constructor and indexer etc.

Consider the program:

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

namespace ConsoleApplication1
{
    class Demo
    {
        private int a, b, c;

		//function definition with default arguments
        public void setValue(int X, int Y = 10, int Z = 20) 
        {
            a = X;
            b = Y;
            c = Z;
        }

		//printing the values
        public void printValue()
        {
            Console.WriteLine("Values are : " + a + ", " + b + ", " + c);
        }
		
    }

	class Program
	{
		static void Main()
		{
			Demo D = new Demo();

			//passing one argument other will be assigned
			//with default arguments
			D.setValue(5);
			D.printValue();            
			//passing two arguments other will be assigned
			//with default arguments
			D.setValue(5, 8);
			D.printValue();
			//passing all arguemnts
			D.setValue(5, 8, 13);
			D.printValue();
		}
	}
}

Output

Values are : 5, 10, 20
Values are : 5, 8, 20
Values are : 5, 8, 13




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.