Find the output of C#.Net programs | default Arguments | Set 2: Enhance the knowledge of C#.Net default Arguments concepts by solving and finding the output of some C#.Net programs.
Question 1:
using System;
namespace Demo
{
class Program
{
static int ret()
{
return 10;
}
static void fun(int a, int b = 50, int c = ret())
{
Console.WriteLine("A: " + a + ", B: " + b + ", C: " + c);
}
//Entry point of the program
static void Main(string[] args)
{
fun(10, 20, 40);
fun(10, b: 20);
}
}
}
Question 2:
using System;
namespace Demo
{
class Program
{
static void fun(int a, int b = 50, int c = sizeof(int))
{
Console.WriteLine("A: " + a + ", B: " + b + ", C: " + c);
}
//Entry point of the program
static void Main(string[] args)
{
fun(10, 20, 40);
fun(10, b: 20);
}
}
}
Answer 1:
Output:
Explanation:
The above program will generate syntax error because we can use an only a compile-time constant for default arguments, we cannot use method call for default argument,
static void fun(int a, int b = 50, int c = ret())
In the above method definition, we called method ret(), which is not correct.
Answer 2:
Output:
Explanation:
In the above program, we create a class Program that contains two static methods fun() and Main() and here we used sizeof(int) that is 4, as a default value for argument c in fun() method.
The method fun() contains three arguments a, b, and c. Here, arguments b and c are used as default arguments. It means if we did not pass the values of 2nd or 3rd argument in the method fun(), then it takes use default values.
Now coming to the Main() method, this is an entry point for program execution,
fun(10, 20, 40);
The above method call will print "A: 10, B: 20, C: 40" on the console screen,
fun(10, b:20);
The above method call will print "A: 10, B: 20, C: 4" on the console screen. Here we used the default value of argument 'c'.
need an explanation for this answer? contact us directly to get an explanation for this answer