Q:

C#.Net find output programs (default Arguments) | set 2

belongs to collection: C#.Net find output programs

0

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);
        }
    }
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer 1:

Output:

main.cs(11,52): error CS1736: The expression being assigned to 
optional parameter `c' must be a constant or default value

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:

A: 10, B: 20, C: 40
A: 10, B: 20, C: 4
Press any key to continue . . .

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

total answers (1)

C#.Net find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C#.Net find output programs (Parameter Passing) | ... >>
<< C#.Net find output programs (default Arguments) | ...