C# / Object-Oriented Programming in C#
Introduction to OOP in C#
This tutorial will introduce you to the basics of Object-Oriented Programming (OOP) in C#. You will learn about the principles that underpin OOP and how it is implemented in C#.
Section overview
5 resourcesCovers object-oriented programming concepts such as classes, objects, inheritance, and polymorphism.
Introduction
In this tutorial, we are going to get familiar with Object-Oriented Programming (OOP) in C#. OOP is a programming paradigm that revolves around the concept of objects, which can contain data and code.
By the end of this tutorial, you will have a basic understanding of:
- The four principles of OOP: Encapsulation, Inheritance, Polymorphism, and Abstraction.
- How to implement these principles in C#.
Prerequisites:
- Basic understanding of C# syntax
- An installed version of .NET SDK
- A text editor or IDE such as Visual Studio
Step-by-Step Guide
Encapsulation
Encapsulation is the practice of keeping fields within a class private, then providing access to them via public methods. It's a protective barrier that keeps the data and code safe from outside interference and misuse.
Example:
public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
In this example, the name field is private, so it can only be accessed within the Employee class. We provide a way to get and set the name with the Name property.
Inheritance
Inheritance is a process in which one class acquires the properties and functionalities of another class. The class whose properties and functionalities are inherited is known as the base class, and the class that inherits those properties and functionalities are known as the derived class.
Example:
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Barking...");
}
}
In this example, the Dog class inherits from the Animal class.
Polymorphism
Polymorphism allows actions to act differently based on the object that they are acting upon. In C#, polymorphism is implemented using many techniques such as method overriding and interfaces.
Example:
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("The animal makes a sound");
}
}
public class Pig : Animal
{
public override void MakeSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
In this example, Animal has a method MakeSound, and the Pig class overrides this method.
Abstraction
Abstraction means using simple things to represent complexity. In C#, we use abstract classes and interfaces to achieve abstraction.
Example:
public abstract class Animal
{
public abstract void animalSound();
}
public class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}
In this example, Animal is an abstract class, and animalSound is an abstract method. The Pig class provides the implementation for animalSound method.
Code Examples
Let's see some practical examples:
- Encapsulation
public class Bank
{
private double balance;
public double Balance
{
get { return balance; }
private set { balance = value; }
}
public void Deposit(double amount)
{
if(amount > 0)
Balance += amount;
}
public void Withdraw(double amount)
{
if(amount > 0 && Balance >= amount)
Balance -= amount;
}
}
In this example, the balance field is private. We can manipulate it through Deposit and Withdraw methods, but we can't directly change its value from outside the class.
- Inheritance
public class Vehicle
{
public string Brand { get; set; }
}
public class Car : Vehicle
{
public int Doors { get; set; }
}
In this example, Car class inherits from Vehicle class. So, Car has both Brand and Doors properties.
- Polymorphism
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape.");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
In this example, the Shape class has a Draw method, and the Circle class overrides this method to draw a circle.
- Abstraction
public abstract class Shape
{
public abstract void Draw();
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle.");
}
}
In this example, Shape is an abstract class with an abstract method Draw. The Circle class provides the implementation for Draw method.
Summary
In this tutorial, you've learned about the four principles of OOP in C#: Encapsulation, Inheritance, Polymorphism, and Abstraction. Understanding these principles will help you design your code in a more organized and efficient way.
For further learning, you can look into more advanced topics such as Interfaces, Generics, and Delegates in C#.
Practice Exercises
-
Create a
Personclass with propertiesNameandAge, and a methodGreetwhich outputs "Hello, my name is {Name} and I am {Age} years old". -
Create a
Studentclass that inherits from thePersonclass, with an additional propertyGrade. Override theGreetmethod to also include the grade of the student. -
Create a
Shapeabstract class with an abstract methodCalculateArea. Then, createSquareandCircleclasses that inherit fromShapeand implement theCalculateAreamethod.
Remember to test your classes by creating an instance of each and invoking their methods. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article