What is the output of this C# program?
using System; class Program { static void Print(int x) { Console.WriteLine("Integer: " + x); } static void Print(string x) { Console.WriteLine("String: " + x); } static void Main() { Print(5); Print("hello"); } }
Look at the method signatures and which one matches the argument type.
The method Print(int x) is called when an integer is passed, and Print(string x) is called when a string is passed. So the output matches the argument types.
What will this program print?
using System; class Program { static void Show(int x, int y = 10) { Console.WriteLine(x + y); } static void Show(int x) { Console.WriteLine(x * 2); } static void Main() { Show(5); } }
Check if these two methods can coexist with these signatures.
These two methods cause a compile-time error because Show(int x) and Show(int x, int y = 10) have ambiguous calls when calling Show(5). The compiler cannot decide which method to call.
Why does this code cause a compilation error?
using System; class Program { static void Display(params int[] numbers) { Console.WriteLine("Params method"); } static void Display(int x, int y) { Console.WriteLine("Two int method"); } static void Main() { Display(1, 2); } }
Think about how the compiler chooses between a params method and a fixed parameter method.
The call Display(1, 2) matches both Display(int x, int y) and Display(params int[] numbers). However, the compiler prefers the method with fixed parameters over the params array, so Display(int x, int y) is called.
What is the output of this program?
using System; class Animal {} class Dog : Animal {} class Program { static void Speak(Animal a) { Console.WriteLine("Animal speaks"); } static void Speak(Dog d) { Console.WriteLine("Dog barks"); } static void Main() { Animal a = new Dog(); Speak(a); } }
Consider the static type of the variable used in the method call.
The variable a is of type Animal, so the method Speak(Animal a) is called, even though the actual object is a Dog. Method overloading is resolved at compile time based on variable type.
What is the output of this program?
using System; class Program { static void Modify(ref int x) { x = x + 10; } static void Modify(out int x) { x = 20; } static void Main() { int a = 5; Modify(ref a); Console.WriteLine(a); int b; Modify(out b); Console.WriteLine(b); } }
Note how ref and out parameters differ and how they affect method selection.
The call Modify(ref a) calls the method with ref parameter, adding 10 to 5 resulting in 15. The call Modify(out b) calls the method with out parameter, setting b to 20. So the output is 15 and then 20.