Object-Oriented Programming (OOP) is a programming paradigm that uses objects to represent real-world entities and provides mechanisms to manipulate these objects. C# is an object-oriented programming language that supports various OOP concepts.
The main concepts of OOP in C# are:
1. Classes: A class is a blueprint for creating objects. It contains the definition of the properties, methods, and events that an object of that class can possess.
“`csharp
public class Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Methods
public void Speak()
{
Console.WriteLine($”My name is {Name} and I’m {Age} years old.”);
}
}
“`
2. Objects: An object is an instance of a class. It represents a specific entity or concept and can be created using the `new` keyword.
“`csharp
Person john = new Person();
john.Name = “John”;
john.Age = 30;
john.Speak();
“`
3. Inheritance: Inheritance allows a class to inherit properties and methods from another class. The class being inherited from is called the base class or parent class, and the class inheriting from it is called the derived class or child class.
“`csharp
public class Student : Person
{
// Additional properties specific to students
public int GradeLevel { get; set; }
}
Student alice = new Student();
alice.Name = “Alice”;
alice.Age = 17;
alice.GradeLevel = 12;
alice.Speak();
“`
4. Encapsulation: Encapsulation is the process of hiding the internal details of a class and exposing only the necessary functionality through methods and properties. Encapsulation helps in maintaining the integrity and security of an object.
“`csharp
private string password;
public string Password
{
get { return password; }
set { password = value; }
}
“`
5. Polymorphism: Polymorphism allows objects of different types to be treated as objects of a common base type. It provides the ability to use a single interface or base class to represent multiple implementations.
“`csharp
public abstract class Shape
{
public abstract double CalculateArea();
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double CalculateArea()
{
return Width * Height;
}
}
“`
OOP allows for code reusability, modularity, and easier maintenance of code. It helps in organizing complex systems and provides a way to model real-world scenarios in a programming language.