Object-Oriented Programming (OOP) is a fundamental programming paradigm supported strongly by C#. It helps in designing software by organizing code around objects and classes, making it easier to maintain, extend, and reuse. Below are detailed questions and answers covering core OOP concepts in C# that will help you understand and master OOP principles, terminology, and features in C#.
Object-Oriented Programming is a programming paradigm based on the concept of “objects” that contain data and behavior. In OOP, software is designed by creating classes which act as blueprints for objects. Objects encapsulate state (data) and operations (methods) that manipulate that state.
OOP promotes concepts like encapsulation, inheritance, polymorphism, and abstraction to build modular and reusable code.
A class in C# is a blueprint or template for creating objects. It defines fields (data members), properties, methods, and events.
An object is an instance of a class. When a class is instantiated using the new keyword, an object is created in memory with its own copy of the class members.
class Car
{
public string Make;
public void Drive()
{
Console.WriteLine("Driving...");
}
}
Car myCar = new Car();
myCar.Make = "Toyota";
myCar.Drive();
Encapsulation is the concept of restricting direct access to an object's data and only allowing it through well-defined interfaces (methods/properties). This hides the internal state and protects object integrity.
In C#, encapsulation is implemented using access modifiers like private, protected, internal, and public. Typically, fields are declared private and accessed via public properties or methods.
class Account
{
private decimal balance;
public decimal Balance
{
get { return balance; }
private set { balance = value; } // private setter
}
public void Deposit(decimal amount)
{
if (amount > 0)
Balance += amount;
}
}
Inheritance allows a new class (derived class) to inherit members from an existing class (base class), promoting code reuse and logical hierarchy.
Example:
class Animal
{
public void Eat() { Console.WriteLine("Eating"); }
}
class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking"); }
}
Dog dog = new Dog();
dog.Eat(); // Inherited from Animal
dog.Bark(); // Defined in Dog
C# supports:
Polymorphism means "many forms." It allows objects to be treated as instances of their base class but to behave differently depending on their actual derived class.
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing Shape");
}
}
class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing Circle");
}
}
Shape s = new Circle();
s.Draw(); // Calls Circle.Draw()
Abstraction means hiding the complex implementation details and showing only essential features. It simplifies usage and reduces complexity.
In C#, abstraction can be achieved via abstract classes and interfaces:
abstract class Vehicle
{
public abstract void Start();
}
class Car : Vehicle
{
public override void Start()
{
Console.WriteLine("Car started");
}
}
| Aspect | Abstract Class | Interface |
|---|---|---|
| Members | Can have fields, constructors, and method implementations. | Only method/property/event declarations (except default implementations in C# 8+). |
| Multiple inheritance | No. A class can inherit only one abstract class. | Yes. A class can implement multiple interfaces. |
| Use case | When closely related classes share implementation. | To define a contract that multiple unrelated classes can implement. |
| Access modifiers | Supports various access modifiers. | All members are public by default. |
A constructor is a special method invoked automatically when an object is created. It initializes the object state.
A destructor is a method called when an object is destroyed or garbage collected, used to release unmanaged resources.
class Person
{
public string Name;
public Person(string name) // Constructor
{
Name = name;
}
~Person() // Destructor
{
Console.WriteLine("Destructor called");
}
}
class Calculator
{
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b; // Overloading
}
class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
A sealed class cannot be inherited by other classes. This is useful to prevent further inheritance when necessary.
A sealed method prevents further overriding of an inherited virtual method in subclasses.
sealed class FinalClass
{
// Cannot be inherited
}
class Base
{
public virtual void Display() { Console.WriteLine("Base Display"); }
}
class Derived : Base
{
public sealed override void Display() { Console.WriteLine("Derived Display"); }
}
class FurtherDerived : Derived
{
// Cannot override Display() here because it is sealed in Derived
}
Properties provide a flexible mechanism to read, write or compute private fields. They use get and set accessors to control access to fields, supporting encapsulation.
class Person
{
private string name;
public string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
name = value;
}
}
}
| Feature | Class | Struct |
|---|---|---|
| Type | Reference Type | Value Type |
| Memory Allocation | Heap | Stack |
| Inheritance | Supports inheritance | Cannot inherit from another struct or class |
| Default Constructor | Can define custom constructor | Cannot define a parameterless constructor |
| Nullability | Can be null | Cannot be null unless nullable struct |
Interfaces define contracts that classes or structs must follow. They declare methods, properties, events, or indexers without implementation (until C# 8.0). Implementing interfaces enables polymorphism and decouples the code by defining behavior without specifying implementation.
interface ILogger
{
void Log(string message);
}
class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
object obj = "Hello";
if (obj is string)
{
Console.WriteLine("obj is a string");
}
string s = obj as string;
if (s != null)
{
Console.WriteLine("obj was cast successfully");
}
A namespace is a container for classes and other types, used to organize code and prevent name conflicts. It provides a way to logically group related classes.
namespace MyApplication.Models
{
class User { }
}
namespace MyApplication.Services
{
class UserService { }
}
new keyword to hide the base class method without overriding it. Calls to the method depend on the reference type.class Base
{
public virtual void Show() { Console.WriteLine("Base Show"); }
}
class Derived : Base
{
public new void Show() { Console.WriteLine("Derived Show"); }
}
Base b = new Derived();
b.Show(); // Calls Base.Show() because of method hiding
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved