Govt. Exams
Entrance Exams
Advertisement
Topics in C# Programming
In C#, what happens when you apply the 'static' modifier to a method inside an interface (C# 11+)?
Correct Answer:
B. The method provides a default implementation and can be called without instantiation
EXPLANATION
C# 11 allows static abstract members in interfaces. Static methods in interfaces provide default implementations and can be called via the interface type.
What is the output of the following code?
class Base { public virtual void Method() { Console.WriteLine("Base"); } }
class Derived : Base { public override void Method() { base.Method(); Console.WriteLine("Derived"); } }
Derived d = new Derived();
d.Method();
class Base { public virtual void Method() { Console.WriteLine("Base"); } }
class Derived : Base { public override void Method() { base.Method(); Console.WriteLine("Derived"); } }
Derived d = new Derived();
d.Method();
Correct Answer:
C. BaseDerived
EXPLANATION
The 'base' keyword calls the parent class method first, printing 'Base', then the derived method prints 'Derived'. Output: 'BaseDerived'.
What will happen if you try to override a non-virtual method?
Correct Answer:
B. Compilation error - cannot override non-virtual method
EXPLANATION
To override a method, it must be marked as 'virtual' in the base class. Attempting to override a non-virtual method causes a compilation error.
Consider the following code. What will be the output?
interface I1 { void Show(); }
interface I2 { void Show(); }
class C : I1, I2 { public void Show() { Console.WriteLine("C"); } }
C obj = new C();
obj.Show();
interface I1 { void Show(); }
interface I2 { void Show(); }
class C : I1, I2 { public void Show() { Console.WriteLine("C"); } }
C obj = new C();
obj.Show();
Correct Answer:
A. C
EXPLANATION
A single method implementation satisfies both interface contracts. The method is called and prints 'C'.
What is the output of the following?
class A { public void Test() { Console.WriteLine("A"); } }
class B : A { public new void Test() { Console.WriteLine("B"); } }
A a = new B();
a.Test();
class A { public void Test() { Console.WriteLine("A"); } }
class B : A { public new void Test() { Console.WriteLine("B"); } }
A a = new B();
a.Test();
Correct Answer:
A. A
EXPLANATION
Using 'new' keyword hides the method. Since reference is of type A, A's Test() is called. Output is 'A'.