Object-oriented programming offers a sustainable way to write spaghetti code. It lets you accrete programs as a series of patches. - Author: Paul Graham. If you are not familiar with OOP, do not worry. I will explain it using real-life examples. We will do a lot of exercises together.
Let's start with real-life objects. İmagine that there is a university like in the picture. There are 4 classes and many desks. As you see that the number of desks and the size of classes are differents. Depending on their functionalities, each class has its own properties and common properties. Instead of writing each room and room's properties separately, we define a class and create instances of it that helps us to avoid repetitions and become more productive. Now, let's define a class and create instances of it in c#.
C# Classes
When you create a project, you see codes similar to the codes below in your program.cs. Let's define some classes and create some instances of them to clarify.
using System;
namespace <ProjectName> {// It's the name that you used when creating the project.
<access specifier> class <ClassName>
{
<access specifier> <data types> variableName;
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
}
Access Specifiers(Modifiers)
public is a keyword that allows all classes to access the code. When you use private, you can only access the code within the same class. If you use protected, you can access the code within the same class and can access the code within the child classes. If you use internal, you can access the code only within its own assembly.
There is a summary table on the Microsoft c# Docs.
Exercise 1
In this exercise, i created a constructor named Room the same as the class name that is a member of a class. It is executed when a class object is created. Note that the name of the constructor has to be the same as the class name.
class Room {
// Here we count the number of rooms. Make it private to avoid
public static int numberOfRoom = 0;changes from invalid user.
int capacity;// Each room have its own capacity
string owner;//The name of owner
int rent;// How much does it cost to rent this room?
/*public Room()// This is a constructor.
{
}*/
// This is a constructor too. We are overloading it by changing the number of paramters
public Room(int capacity, string owner, int rent)
{
this.capacity = capacity;
this.owner = owner;
this.rent = rent;
numberOfRoom += 1;// When you create an instance of room, the numberOfRomm icreases.
}
public override string ToString()
{
return $"Room: {numberOfRoom} \t Capacity: {this.capacity}\tOwner: {this.owner}\nRent: {this.rent}";
}
/*public int getTheTotalNumberOfRooms()
{
return numberOfRoom;
}*/
}
Now, we create 3 instances of Room class and get informations about them.
namespace MyProject {
class Program {
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Room room1 = new Room(5,"Bob",1000);
Room room2 = new Room(8, "Jack", 1500);
Room room3 = new Room(10, "Elon", 2000);
Console.WriteLine(room1.ToString());
Console.WriteLine(room2.ToString());
Console.WriteLine(room3.ToString());
Console.WriteLine($"Total number of rooms: {Room.numberOfRoom} ");
}
}
}
Exercise 2
Now we will create a User class and Product Class. Every user can sell or rent a product, update all the information of the product and print all information about User and User's products. Open the solution explorer => right click the project name => Add + New Item => create Product and User classes. Now you are ready to copy the code below.
class User {
static int countUsers = 0;
string firstName;
string lastName;
string tel;
List<Product> products;
public User(string firstName, string lastName, string tel)
{
products = new List<Product>();// We keep products in a list.
this.firstName = firstName;
this.lastName = lastName;
this.tel = tel;
countUsers += 1;
}
// To secure data, we used private access modifier. So, we added a getter method.
public string FirstName { get => firstName; }
public string LastName { get => lastName; }
public string Tel { get => tel; }
public override string ToString()// We override default ToString method to customize it.
{
string info = "Products: ";
if (products.Count >= 1)
{
foreach (Product item in products)
{
info += item.ToString();
}
return $"First name: {FirstName}\t Last name: {LastName}\t Tel:{Tel}\n {info}";
}
return $"First name: {FirstName}\t Last name: {LastName}\t Tel:{Tel}\n {info}-";
}
// changes first name.
public void ChangeUserInfo(string newFirstName)
{
this.firstName = newFirstName;
}
// changes first name and last name.
public void ChangeUserInfo(string newFirstName, string newLastName)
{
this.firstName = newFirstName;
}
// changes first name, last name and Tel.
public void ChangeUserInfo(string newFirstName, string newLastName, string newTel)
{
this.firstName = newFirstName;
this.lastName = newLastName;
this.tel = newTel;
}
// If the product is not in the list, we add the product into our list.
public void SellProduct(string title, string details, string options, int price)
{
Product newProduct = new Product(title, details, options, price);
if (!products.Contains(newProduct))
{
this.products.Add(newProduct);
}
}
public void ModifyProduct(string title, string details, string options, int price)
{
foreach (Product product in products)
{
if (product.Title.Equals(title))
{
product.Details = details;
product.Options = options;
product.Price = price;
}
}
}
}
The code of Product class is below.
class Product {
static short count = 0; // is the number of products
string publicationTime;
string title;
string details;
string options;
int price;
public Product( string title, string details, string options, int price)
{
DateTime time = DateTime.Now;
this.publicationTime = time.Day + "/" + time.Month + "/" + time.Year + " " + time.Hour + ":" + time.Minute;
this.title = title;
this.Details = details;
this.Options = options;
this.price = price;
count += 1;
}
public string Options { get => options; set => options = value; }
public int Price { get => price; set => price = value; }
public string Title { get => title; set => title = value; }
public string Details { get => details; set => details = value; }
public override string ToString()
{
return $"Published at: {this.publicationTime}\nTitle:{Title}\nDetails: {Details}\nOption:{Options}\nPrice:{Price}\n";
}
}
Let’s create some instances in the main funtion.
static void Main(string[] args)
{
User user1 = new User("Bob", "Dylan", "4440444");// (firstName, lastName, Tel)
Console.WriteLine(user1.ToString());
user1.SellProduct("Guitar", "Retro guitar", "rent", 1000);//(title, details,option, price)
Console.WriteLine(user1.ToString());
user1.SellProduct("Computer", "The camera is down", "sell", 100);
Console.WriteLine(user1.ToString());
}
}