What is the difference between an interface and an abstract class?
public interface IPayable { decimal Pay(); }
public abstract class Employee : IPayable { public string Name=""; public abstract decimal Pay(); }17 Interfaces & Abstract Classes interview questions for C# roles, each with a model answer, examples and likely follow-ups.
17 questionsWhat is the difference between an interface and an abstract class?
public interface IPayable { decimal Pay(); }
public abstract class Employee : IPayable { public string Name=""; public abstract decimal Pay(); }Why program to an interface rather than a concrete type?
public OrderService(IOrderRepository repo) { }What are default interface methods and when are they useful?
interface ILogger { void Log(string m); void LogError(string m) => Log("ERR: "+m); }Can a class implement two interfaces with the same method? How is it resolved?
class C : IA, IB { void IA.Do(){} void IB.Do(){} }When would you choose an abstract class over an interface for extensibility?
public abstract class HttpHandlerBase { protected readonly HttpClient Http; ... }What is the Interface Segregation Principle and how does it apply in C#?
// instead of IRepository with 20 methods:
interface IReadRepository<T> { Task<T?> GetAsync(int id); }What is an interface, and what can (and can't) it contain in its most basic form?
public interface IShape {
double CalculateArea(); // no implementation, just a contract
double Perimeter { get; } // property signature only
}
public class Circle : IShape {
public double Radius { get; set; }
public double CalculateArea() => Math.PI * Radius * Radius;
public double Perimeter => 2 * Math.PI * Radius;
}What is an abstract class, and how does it differ from a fully concrete base class?
public abstract class Animal {
public string Name { get; set; } = "";
public abstract void MakeSound(); // must be implemented by subclasses
public void Sleep() => Console.WriteLine($"{Name} is sleeping."); // shared, concrete implementation
}
// new Animal(); // Error: cannot instantiate an abstract classHow do you decide between using an interface versus an abstract class for a given design?
// Interface: unrelated types sharing a CAPABILITY
public interface IFlyable { void Fly(); }
public class Bird : IFlyable { public void Fly() { } }
public class Airplane : IFlyable { public void Fly() { } }
// Abstract class: related types sharing an IDENTITY and implementation
public abstract class Animal { public abstract void MakeSound(); }How do default interface methods (C# 8+) let an interface provide implementation, and what backward-compatibility problem do they solve?
public interface ILogger {
void Log(string message);
void LogError(string message) => Log($"ERROR: {message}"); // default implementation, C# 8+
}
public class ConsoleLogger : ILogger {
public void Log(string message) => Console.WriteLine(message);
// LogError is inherited automatically -- no need to implement it
}
Showing 1–10 of 17