Govt. Exams
Entrance Exams
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.
class Animal { public virtual void Sound() { Console.WriteLine("Generic Sound"); } }
class Dog : Animal { public override void Sound() { Console.WriteLine("Bark"); } }
Dog dog = new Dog();
dog.Sound();
Polymorphism ensures that the overridden method in Dog class executes. The override keyword allows the derived class to provide its specific implementation.
Records (introduced in C# 9) are reference types designed for immutability with built-in equality comparison and ToString() methods.
Composition represents a 'has-a' relationship where one class contains objects of another class. Here, Library 'has-a' Book collection.