Govt. Exams
Entrance Exams
class A { public A() { Console.WriteLine("A"); } }
class B : A { public B() { Console.WriteLine("B"); } }
class C : B { public C() { Console.WriteLine("C"); } }
new C();
Constructor execution follows from parent to child. When C() is called, it implicitly calls B() which calls A(). So output is: A B C. Base class constructors execute before derived class constructors.
IComparable interface requires implementing the CompareTo() method, which defines how objects of the class should be compared for sorting purposes.
Interfaces define contracts that unrelated classes can implement. If classes have common inheritance relationship, abstract classes are better. Interfaces support multiple implementation, making them ideal for unrelated classes.
class Test
{
public Test() { Console.WriteLine("Constructor"); }
~Test() { Console.WriteLine("Destructor"); }
}
Test t = new Test();
t = null;
The constructor runs immediately when the object is created. The destructor (finalizer) is called by the garbage collector when the object is destroyed, which happens later, not immediately when t = null.
Classes are reference types (stored on heap), while structs are value types (stored on stack). This affects memory management and performance characteristics differently.
This is polymorphism - the ability of different derived classes to override the same abstract method with different implementations. While abstraction is also involved, polymorphism is the primary principle being demonstrated.
public class Base
{
public virtual void Display() { Console.WriteLine("Base"); }
}
public class Derived : Base
{
public override void Display() { Console.WriteLine("Derived"); }
}
Base obj = new Derived();
obj.Display();
This demonstrates polymorphism. Even though the reference is of type Base, the actual object is Derived. The overridden method in Derived class is called, printing 'Derived'.
Nullable reference types (enabled from C# 8) provide compile-time checks for null references, helping prevent NullReferenceException at runtime.
The 'is' operator returns a boolean indicating type compatibility. The 'as' operator performs type conversion and returns null if the conversion fails (no exception).
Abstract classes cannot be instantiated. Derived classes must provide concrete implementations of all abstract methods, enforcing a contract.