Menu
CoddyTech

OOPs in C# Interview Questions

Classes, inheritance, polymorphism, interfaces and the keywords virtual, override, new and sealed.

12 questions
  1. 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 (virtual and override at run time, overloading at compile time) and abstraction (abstract classes and interfaces, which define what a type does without fixing how).

  2. 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.

  3. How do override and new behave 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());
        }
    }

    Who is virtual and overridden, so the call dispatches on the runtime type and returns "B". Name is hidden with new, and a hidden method is chosen by the variable's compile-time type (A), so it returns "A". Without new you get warning CS0108 and the same behavior.

  4. 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 virtual or abstract method 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.

  5. 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 second new skips the static constructor. An exception in a static constructor leaves the type unusable (TypeInitializationException).

  6. 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 get and set methods 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);
        }
    }
  7. 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);
        }
    }

    P is a struct, a value type, so var p2 = p1 copies the value and p1.X stays 1. C is a class, so c1 and c2 point at one object and c1.X becomes 2. Use structs for small, immutable, value-like data such as DateTime.

  8. What does the sealed keyword do in C#?

    A sealed class cannot be inherited, and a sealed override method 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.

  9. What is a static class in C#, and when do you use static members?

    A static class cannot be instantiated or inherited and holds only static members; use it for stateless helpers such as Math and 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, then 1 2 2: Id is per object, Created is shared. See static.

  10. 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());
        }
    }
  11. 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.

  12. What is the difference between is and as in C#?

    is tests type compatibility and returns bool (since C# 7 it can also declare a typed variable); as converts and returns null on failure, where a cast (T)x throws InvalidCastException.

    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 int does not compile, because as needs a reference or nullable type.

Coddy programming languages illustration

Learn to code with Coddy

Get started