Recently I heard an interesting question on function overloading. In this post let's see that question and find the answer.
In one of the previous post explained about what is function overloading. You can read the post to know more on function overloading.
The program showing function overloading interview question:
{
class Program
{
static void Main(string[] args)
{
// Question 1
Method(new object());
// Question 2
Method("Interview Question");
// Question 3
bject obj = GetText();
Method(obj);
// Question 4
Method(null);
Console.ReadLine();
}
public static object GetText()
{
return "function overloading";
}
public static void Method(object obj)
{
if (obj == null){ Console.WriteLine("Object is null.");}
else { Console.WriteLine(obj.GetType().Name); }
}
public static void Method(string text)
{
if (string.IsNullOrEmpty(text))
{
Console.WriteLine("String is null.");
}
else
{
Console.WriteLine(text));
}
}
}
}
Answers for the function overloading interview questions:
-
Question 1 answer: It's straight forward question. It prints "Object" to the console. In function overloading binding happens at compile time and hence the method which takes the object as parameter is invoked.
-
Question 2 answer: It's another simple one. It prints "Interview Question" to the console. In function overloading binding happens at compile time and hence the method which takes the string as parameter is invoked.
-
Question 3 answer: It prints "string" to the console and not "function overloading". At compile time obj is of type object and not string type.
-
Question 4 answer: It's needs thinking. Both object type and string type variable can be null. When null is passed as parameter value, the more specific type, in this case string parameter method is bounded at the time of compilation. Hence it prints "String is null" to the console.
No comments:
Post a Comment