Govt. Exams
Entrance Exams
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.
Properties with accessors (get/set) follow encapsulation principles, allowing controlled access while maintaining data validation logic within the property.
The 'virtual' keyword marks a method in the base class as overridable. Derived classes can use 'override' to provide their own implementation.
'where' clause in generic types constrains type parameters (e.g., where T : class, where T : IComparable). C# 11 added 'allows ref struct' constraint.
Composition (HAS-A) and Inheritance (IS-A) serve different purposes. Composition is more flexible and often preferred over inheritance to avoid tight coupling.
Explicit interface implementation is always private by convention and accessed through interface reference only, not through class instance directly.
Records (C# 9+) are designed for immutable data with positional parameters, automatic value-based equality, and ToString() implementation.
If you override a non-virtual method, C# will hide it and show a compiler warning. Use 'new' keyword to suppress the warning and explicitly hide the base method.