Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects" β entities that combine data and behavior. C# is a modern, object-oriented programming language that fully supports OOP principles and makes extensive use of classes as blueprints for creating objects.
OOP organizes software design around data, or objects, rather than functions and logic. An object is an instance of a class and encapsulates state (attributes) and behavior (methods). The main goal of OOP is to model real-world entities and relationships in code, making programs easier to understand, maintain, and extend.
The four fundamental principles of OOP are:
A class in C# is a user-defined data type that acts as a blueprint for creating objects. It defines properties (data fields), methods (functions), constructors, and other members.
public class Car
{
// Fields (attributes)
public string Make;
public string Model;
public int Year;
// Constructor
public Car(string make, string model, int year)
{
Make = make;
Model = model;
Year = year;
}
// Method (behavior)
public void Drive()
{
Console.WriteLine($"{Make} {Model} is driving.");
}
}
An object is an instance of a class created using the new keyword.
Car myCar = new Car("Toyota", "Camry", 2020);
myCar.Drive(); // Output: Toyota Camry is driving.
Encapsulation hides internal object details and exposes only what is necessary via access modifiers:
| Modifier | Accessibility |
|---|---|
| public | Accessible from anywhere |
| private | Accessible only within the class |
| protected | Accessible within the class and derived classes |
| internal | Accessible within the same assembly |
| protected internal | Accessible within the same assembly or derived classes |
Instead of exposing fields directly, properties are used to control access:
public class Person
{
private string name; // Private field
// Public property with getter and setter
public string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
name = value;
}
}
}
C# allows simplified property declaration:
public class Person
{
public string Name { get; set; }
}
Constructors initialize new objects. They have the same name as the class and no return type.
public class Book
{
public string Title;
public string Author;
public Book(string title, string author)
{
Title = title;
Author = author;
}
}
If no constructor is declared, the compiler creates a parameterless default constructor.
You can define multiple constructors with different parameters:
public class Rectangle
{
public int Width;
public int Height;
public Rectangle()
{
Width = 0;
Height = 0;
}
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
}
Inheritance allows a class to acquire properties and methods from a base class. It supports reusability and polymorphism.
public class Vehicle
{
public void Start() { Console.WriteLine("Vehicle started."); }
}
public class Car : Vehicle
{
public void Drive() { Console.WriteLine("Car is driving."); }
}
Car car = new Car();
car.Start(); // Inherited method
car.Drive(); // Own method
Used to call members of the base class explicitly.
public class BaseClass
{
public void Show() { Console.WriteLine("Base Show"); }
}
public class DerivedClass : BaseClass
{
public void Show()
{
base.Show(); // Call base class Show
Console.WriteLine("Derived Show");
}
}
Polymorphism allows objects of different types to be treated as objects of a common base type, typically via method overriding.
Virtual methods can be overridden by derived classes.
public class Animal
{
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Dog barks");
}
}
Method calls are resolved at runtime:
Animal myAnimal = new Dog();
myAnimal.Speak(); // Output: Dog barks
Abstraction focuses on exposing only relevant information. In C#, it is supported by abstract classes and interfaces.
Cannot be instantiated and may contain abstract methods that derived classes must implement.
public abstract class Shape
{
public abstract double GetArea();
}
public class Circle : Shape
{
public double Radius;
public Circle(double radius)
{
Radius = radius;
}
public override double GetArea()
{
return Math.PI * Radius * Radius;
}
}
Interfaces define a contract without implementation.
public interface IFlyable
{
void Fly();
}
public class Bird : IFlyable
{
public void Fly()
{
Console.WriteLine("Bird is flying.");
}
}
Letβs create classes to model books, library members, and borrowing behavior.
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public bool IsBorrowed { get; private set; }
public Book(string title, string author)
{
Title = title;
Author = author;
IsBorrowed = false;
}
public void Borrow()
{
if (!IsBorrowed)
IsBorrowed = true;
else
Console.WriteLine("Book already borrowed.");
}
public void Return()
{
IsBorrowed = false;
}
}
public class Member
{
public string Name { get; set; }
private List borrowedBooks = new List();
public Member(string name)
{
Name = name;
}
public void BorrowBook(Book book)
{
if (!book.IsBorrowed)
{
book.Borrow();
borrowedBooks.Add(book);
Console.WriteLine($"{Name} borrowed {book.Title}");
}
else
{
Console.WriteLine($"{book.Title} is already borrowed.");
}
}
public void ReturnBook(Book book)
{
if (borrowedBooks.Contains(book))
{
book.Return();
borrowedBooks.Remove(book);
Console.WriteLine($"{Name} returned {book.Title}");
}
}
}
In summary, Object-Oriented Programming in C# revolves around the concept of classes and objects. Classes define the blueprint, encapsulating data and behavior, while objects are instances of these classes.
Understanding OOP principles β encapsulation, abstraction, inheritance, and polymorphism β enables developers to write code that is modular, reusable, and easier to maintain. Classes provide a powerful mechanism to model real-world entities and behaviors.
With C#βs robust support for OOP features such as access modifiers, constructors, inheritance, interfaces, and abstract classes, developers can build scalable and flexible applications that are easy to evolve and extend.
Mastering these concepts lays the foundation for effective C# programming and software design.
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