Preparing .NET Interview - Part 3 (Parameters)

Here are the links to previous articles:

I am here to continue series related to .NET interview preparation. Today we will discuss the questions related to parameters and present the answers in easy way.

So, let’s take questions one by one.

  1. What’s the similarity and difference between ref and out parameters and when are they used?

    Answer:

    Ref and out parameters are essentially reference type parameters and used to pass reference of the parameters and due to that any change made in the parameters in the called function will also reflect in the calling function. But they differ in their uses scenario.

    Ref parameter is used when parameter is already initialized in the calling method whereas out is used when we want to enforce parameter initialization in the called method.

    When using ref, failing to initialize parameter in the calling method will give an error and in case of out failing to initialize parameter in the called method with also throw an error.

    Example: Regular parameters
    1. static void Add(int a, int b)  
    2. {  
    3.     a = 5;  
    4.     b = 6;  
    5.     Console.WriteLine("Addition in the method: {0}", a + b);  
    6. }  
    7. static void Main()   
    8. {  
    9.     int num1 = 3;  
    10.     int num2 = 4;  
    11.     Console.WriteLine("Addition before calling method: {0}", num1 + num2);  
    12.     Add(num1, num2);  
    13.     Console.WriteLine("Addition after calling method: {0}", num1 + num2);  
    14. }  
    Output

    output

    Here you can see that in the called function, copy of parameters is passed, hence change made in variables (a, b) is not reflecting back in calling function (i.e. printing 7 only).

    Example: ref parameters
    1. static void Add(refint a, refint b)  
    2. {  
    3.     a = 5;  
    4.     b = 6;  
    5.     Console.WriteLine("Addition in the method: {0}", a + b);  
    6. }  
    7. static void Main()  
    8. {  
    9.     int num1 = 3; ////int num1; will throw an error  
    10.     int num2 = 4; ////int num2; will throw an error  
    11.     Console.WriteLine("Addition before calling method: {0}", num1 + num2);  
    12.     Add(refnum1, refnum2);  
    13.     Console.WriteLine("Addition after calling method: {0}", num1 + num2);  
    14. }  
    Output

    output

    As you can see here that in the called function, since reference of parameters is passed, the change made in variables (a, b) is reflecting back in calling function (i.e. printing 11). Also if we don’t initialize variables (keep intnum1;) it will throw an error as in case of ref, parameter have to be initialized before it passed in the called function

    Example: out parameters
    1. static void Add(out int a, out int b)  
    2. {  
    3.     a = 5; ////Assignment is required else it won't compile.  
    4.     b = 6; ////Assignment is required else it won't compile.  
    5.     Console.WriteLine("Addition in the method: {0}", a + b);  
    6. }  
    7. static void Main()  
    8. {  
    9.     int num1; ////Initialization is not required.  
    10.     int num2; ////Initialization is not required.  
    11.     Add(outnum1, outnum2);  
    12.     Console.WriteLine("Addition after calling method: {0}", num1 + num2);  
    13. }  
    Output

    output

    Here you can see that when using out parameters, initialization of parameters are not required in the calling function, however these parameters must be initialized in the called function else compile time error will be thrown. Further since out parameter also uses reference behind the scene, change made in variables (a, b) is reflecting back in calling function (i.e. printing 11).

  2. Can you return multiple values from a method in C#? If yes, then how?

    Answer:

    By definition, return statement can only return one object or value however there are few workarounds to achieve multiple returns as following.

    • Create an instance of a class or struct which have multiple member variables or properties and assign the values to them and return the class or struct object.
    1. class MyClass  
    2. {  
    3.     public string Name  
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8.     public string City   
    9.     {  
    10.         get;  
    11.         set;  
    12.     }  
    13.     public string State  
    14.     {  
    15.         get;  
    16.         set;  
    17.     }  
    18.     public int Salary   
    19.     {  
    20.         get;  
    21.         set;  
    22.     }  
    23. }  
    24. public class Client  
    25. {  
    26.     static MyClassReturnMultiple()  
    27.     {  
    28.         MyClass myClass = new MyClass();  
    29.         myClass.Name = "Prakash";  
    30.         myClass.City = "Satna";  
    31.         myClass.State = "MP";  
    32.         myClass.Salary = 1000;  
    33.         return myClass;  
    34.     }  
    35.     static void Main()   
    36.     {  
    37.         MyClass myClass = ReturnMultiple();  
    38.         Console.WriteLine("Name: {0}\nCity: {1}\nState: {2}\nSalary: {3}", myClass.Name, myClass.City, myClass.State, myClass.Salary);  
    39.     }  
    Output

    output

    As you can see that using class (or struct) as a return type, we can return multiple values at once.

    • Using output parameters, as in the question 1 above, we saw that values of parameters (a, b) set in called method were later available on the calling method as well hence we were able to return values implicitly.

  3. Can you create a method which can take variable number of arguments? If yes, then what are the constraints attached to it?

    Answer:

    We can pass variable number of parameters using params keyword. When using params, method parameter can vary from zero to infinite in numbers.

    Let’s understand this by simple example.
    1. static void TestRegularAddition(int[] numbers)   
    2. {  
    3.     int sum = 0;  
    4.     foreach(int in numbers)   
    5.     {  
    6.         sum = sum + i;  
    7.     }  
    8.     Console.WriteLine("Inside TestRegularAddition: {0}", sum);  
    9. }  
    10. static void TestParamsAddition(params int[] numbers)  
    11. {  
    12.     int sum = 0;  
    13.     foreach(int in numbers)   
    14.     {  
    15.         sum = sum + i;  
    16.     }  
    17.     Console.WriteLine("Inside TestParamsAddition: {0}", sum);  
    18. }  
    19. static void TestParamsConcatenation(params string[] strings)  
    20. {  
    21.     string str = string.Empty;  
    22.     foreach(string s in strings)  
    23.     {  
    24.         str = str + ' ' + s;  
    25.     }  
    26.     Console.WriteLine("Inside TestParamsConcatenation: {0}", str);  
    27. }  
    28. static void Main()  
    29. {  
    30.     //TestRegularAddition(); //Error: No argument passed  
    31.     //TestRegularAddition(1); //Error: cannot convert int to int[]  
    32.     //TestRegularAddition(1,2); //Error: no overload for method TestRegularAddition takes 2 arguments  
    33.     TestRegularAddition(newint[]   
    34.     {  
    35.         1,  
    36.         2,  
    37.         3  
    38.     }); //Correct  
    39.     TestParamsAddition(); //Correct  
    40.     TestParamsAddition(1); //Correct  
    41.     TestParamsAddition(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //Correct  
    42.     TestParamsConcatenation(); //Correct  
    43.     TestParamsConcatenation("Prakash"); //Correct  
    44.     TestParamsConcatenation("Prakash""Tripathi""Beeda""Amarpatan""Satna""MP"); //Correct  
    45. }  
    Output

    output

    As you can see that regular way of passing parameters has some strict rules whereas params allows us to pass either no parameter or any number of parameters.

    The constraint is that when params is used, additional parameters are not allowed after the params keyword however additional parameters can appear before the params keyword.

  4. What are named and optional parameters in C# and how to use them?

    Answer:

    Named parameter introduced to avoid remembering the order of parameters if we know the names of them. If we are using named parameter along with regular or positioned parameter then named parameter should appear in the last.

    Optional parameter on the other hand allows us to send only required parameters. The conditions when using optional are that optional parameters need to define the default values while declaration also for optional parameters must be defined in the last or after all the required parameters.

    Let’s understand this by simple example.
    1. static void TestNamedParameter(int principle, float rate, int year)  
    2. {  
    3.     Console.WriteLine("Inside TestNamedParameter, Simple Interest is: {0}", (principle * rate * year) / 100);  
    4. }  
    5. static void TestOptionalParameter(int principle, float rate, int year = 1)   
    6. {  
    7.     Console.WriteLine("Inside TestOptionalParameter, Simple Interest is: {0}", (principle * rate * year) / 100);  
    8. }  
    9. static void Main()   
    10. {  
    11.     //TestNamedParameter(rate: 9, principal: 10000, 1); //Error: named parameter should be in last.  
    12.     TestNamedParameter(10000, 9, 1); //Positioned parameter  
    13.     TestNamedParameter(10000, rate: 9, year: 1); //Correct  
    14.     TestNamedParameter(principle: 10000, rate: 9, year: 1); //Correct  
    15.     //TestOptionalParameter(10000); //Error: all required parameters are not passed  
    16.     TestOptionalParameter(10000, 9, 1); //All parameters are passed  
    17.     TestOptionalParameter(10000, 9);  
    18. }  
    Output

    output

    Hope you have liked the article. Look forward for your comments/suggestions.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now