A simple question of C#
Hello o/
I will write a C# program and you have to predict the output of the program.
namespace Test
{
class A
{
public A()
{
Console.WriteLine("A is called");
}
}
class B : A
{
public B()
{
Console.WriteLine("B is called");
}
}
public class Program
{
public static void Main(string[] args)
{
B obj = new B();
}
}
}so, what do you think it will output? the answer isn't that obvious. let me first show you the answer:
A is called
B is called
you might be wondering why it's also printing the constructor of A? we didn't call constructor of A using base() method but still it still got called.
the answer is simple, compiler adds base() call in the child. but why??? so basically to create an instance of any class we have to have some methods defined inside System.Object which we get while creating an object. in simple language this means that in c# to create any class instance you have to call parent constructor implicitly by the compiler of explicitly using base keyword.
I hope you learned something new today!
Comments
Post a Comment