What are the four pillars of OOP, and how does C# support each?
Encapsulation (private fields behind properties), inheritance (one base class, any number of interfaces), polymorphism (
virtualandoverrideat run time, overloading at compile time) and abstraction (abstractclasses and interfaces, which define what a type does without fixing how).What is the difference between an abstract class and an interface in C#?
An abstract class is a partial implementation that a class inherits from (only one); an interface is a contract that a class or struct implements (any number). Only an abstract class can have constructors and instance fields.
Use an abstract class when related types share code and state (
Stream), an interface for a capability unrelated types share (IDisposable). Since C# 8 interfaces can have default method bodies. See interfaces.How do
overrideandnewbehave when called through a base class reference?C#using System; class A { public virtual string Who() { return "A"; } public string Name() { return "A"; } } class B : A { public override string Who() { return "B"; } public new string Name() { return "B"; } } class Program { static void Main() { A x = new B(); Console.WriteLine(x.Who() + x.Name()); } }Whoisvirtualand overridden, so the call dispatches on the runtime type and returns"B".Nameis hidden withnew, and a hidden method is chosen by the variable's compile-time type (A), so it returns"A". Withoutnewyou get warning CS0108 and the same behavior.What is the difference between method overloading and overriding?
Overloading is several methods with one name and different parameters, chosen by the compiler. Overriding is a derived class replacing a
virtualorabstractmethod with the same signature, chosen at run time.C#using System; class Shape { public virtual double Area() { return 0; } } class Circle : Shape { public double R; public Circle(double r) { R = r; } public override double Area() { return Math.Round(Math.PI * R * R, 2); } } class Program { static string Describe(int x) { return "int " + x; } static string Describe(string s) { return "string " + s; } static void Main() { Console.WriteLine(Describe(5)); Console.WriteLine(Describe("five")); Shape s = new Circle(2); Console.WriteLine(s.Area()); } }Trap: methods that differ only by return type are not overloads; they do not compile.
In what order do static, base and derived constructors run?
C#using System; class Base { public Base() { Console.Write("Base "); } } class Derived : Base { static Derived() { Console.Write("Static "); } public Derived() { Console.Write("Derived "); } } class Program { static void Main() { new Derived(); new Derived(); Console.WriteLine(); } }The static constructor runs once, before the first instance. Each
new Derived()then runs the base constructor before the derived one, and the secondnewskips the static constructor. An exception in a static constructor leaves the type unusable (TypeInitializationException).What is the difference between a field and a property in C#?
A field is a variable stored in the object; a property is a pair of
getandsetmethods that reads like a field. Expose public data as properties, so you can add validation later without breaking callers.C#using System; class Account { private decimal balance; // field public string Owner { get; set; } // auto-property public decimal Balance // property with logic { get { return balance; } private set { if (value < 0) throw new ArgumentException("negative"); balance = value; } } public void Deposit(decimal amount) { Balance += amount; } } class Program { static void Main() { var acc = new Account { Owner = "Asha" }; acc.Deposit(250m); Console.WriteLine(acc.Owner + " " + acc.Balance); } }If you copy a struct and change the copy, does the original change? And a class?
C#using System; struct P { public int X; } class C { public int X; } class Program { static void Main() { var p1 = new P { X = 1 }; var p2 = p1; p2.X = 2; var c1 = new C { X = 1 }; var c2 = c1; c2.X = 2; Console.WriteLine(p1.X + " " + c1.X); } }Pis a struct, a value type, sovar p2 = p1copies the value andp1.Xstays 1.Cis a class, soc1andc2point at one object andc1.Xbecomes 2. Use structs for small, immutable, value-like data such asDateTime.What does the
sealedkeyword do in C#?A
sealedclass cannot be inherited, and asealed overridemethod cannot be overridden further down the hierarchy.public sealed class Token { } // class Special : Token { } -> compile error CS0509 class Base { public virtual void Run() { } } class Middle : Base { public sealed override void Run() { } } class Leaf : Middle { /* cannot override Run here */ }Seal classes you did not design for extension; the JIT can also call a sealed type's methods without a virtual call.
What is a static class in C#, and when do you use static members?
A
staticclass cannot be instantiated or inherited and holds only static members; use it for stateless helpers such asMathand for extension methods. A static member belongs to the type, so all callers share one copy.C#using System; static class Temperature { public static double ToFahrenheit(double c) { return c * 9 / 5 + 32; } } class Counter { public static int Created; // one copy shared by every instance public int Id; public Counter() { Created++; Id = Created; } } class Program { static void Main() { Console.WriteLine(Temperature.ToFahrenheit(100)); var a = new Counter(); var b = new Counter(); Console.WriteLine(a.Id + " " + b.Id + " " + Counter.Created); } }It prints
212, then1 2 2:Idis per object,Createdis shared. See static.What is explicit interface implementation, and when do you need it?
Explicit implementation names the member
InterfaceName.Member, so it is callable only through that interface type. Use it when two interfaces declare the same member with different meanings, or to keep a member off the class's public surface.C#using System; interface IPrinter { string Print(); } interface IExporter { string Print(); } class Report : IPrinter, IExporter { string IPrinter.Print() { return "sent to printer"; } string IExporter.Print() { return "exported as PDF"; } } class Program { static void Main() { var r = new Report(); // r.Print(); does not compile: no public Print Console.WriteLine(((IPrinter)r).Print()); Console.WriteLine(((IExporter)r).Print()); } }What are extension methods, and how do you write one?
An extension method is a static method in a static class whose first parameter is marked
this; callers use it like an instance method. It adds behavior to types you cannot change, and LINQ is built this way.C#using System; static class StringExtensions { public static bool IsPalindrome(this string s) { int i = 0, j = s.Length - 1; while (i < j) { if (s[i] != s[j]) return false; i++; j--; } return true; } } class Program { static void Main() { Console.WriteLine("level".IsPalindrome()); Console.WriteLine("coddy".IsPalindrome()); } }An instance method with the same signature wins. See extension methods.
What is the difference between
isandasin C#?istests type compatibility and returnsbool(since C# 7 it can also declare a typed variable);asconverts and returnsnullon failure, where a cast(T)xthrowsInvalidCastException.C#using System; class Program { static void Describe(object o) { if (o is int n) Console.WriteLine("int, doubled: " + n * 2); string s = o as string; Console.WriteLine(s == null ? "not a string" : "string of length " + s.Length); } static void Main() { Describe(21); Describe("hello"); } }Trap:
o as intdoes not compile, becauseasneeds a reference or nullable type.
OOPs in C# Interview Questions
Classes, inheritance, polymorphism, interfaces and the keywords virtual, override, new and sealed.