C# Tutorial menu

C# Classes and Objects

C# is an object-oriented language. A class describes a kind of thing, and an object is one real thing made from that class.

Classes and Objects

ClassObjects
StudentAli, Ayesha, Bilal
CourseWeb Development, Graphic Designing
ProductRice bag, cooking oil

In a top-level program, write your classes after the main code.

Creating a Class

Example

csharp
Student s1 = new Student();
s1.Name = "Ali";
s1.Marks = 76;
s1.Introduce();

Student s2 = new Student { Name = "Ayesha", Marks = 93 };
s2.Introduce();

class Student
{
    public string Name { get; set; } = "";
    public int Marks { get; set; }

    public void Introduce()
    {
        Console.WriteLine($"I am {Name}, my marks are {Marks}");
    }
}
Output
I am Ali, my marks are 76
I am Ayesha, my marks are 93

Name and Marks are properties. { get; set; } means other code can read and change them. The second object is made with an object initializer, which sets properties inside { }.

Constructors

A constructor runs when the object is created. It has the class name and no return type:

Example

csharp
Product oil = new Product("Cooking oil 1L", 620);
Product rice = new Product("Rice 5kg", 1850);
oil.Show();
rice.Show();

class Product
{
    public string Name { get; }
    public int Price { get; }

    public Product(string name, int price)
    {
        Name = name;
        Price = price;
    }

    public void Show() => Console.WriteLine($"{Name}: Rs {Price}");
}
Output
Cooking oil 1L: Rs 620
Rice 5kg: Rs 1850

Properties with only get can be set in the constructor but not changed later. This keeps the object safe.

Encapsulation

Keep data private and allow changes only through methods that check the values:

Example

csharp
BankAccount acc = new BankAccount();
acc.Deposit(10000);
acc.Withdraw(3500);
acc.Withdraw(50000);   // refused
Console.WriteLine($"Balance: Rs {acc.Balance}");

class BankAccount
{
    private int balance = 0;

    public int Balance => balance;

    public void Deposit(int amount)
    {
        if (amount > 0) balance += amount;
    }

    public void Withdraw(int amount)
    {
        if (amount <= balance) balance -= amount;
        else Console.WriteLine("Not enough balance");
    }
}
Output
Not enough balance
Balance: Rs 6500
Access modifierWho can use the member
publicAny code
privateOnly code inside the same class (the default)
protectedThe class and classes that inherit from it
internalAny code in the same project

Inheritance

A class can inherit from another with :. Mark a method virtual to let child classes change it with override:

Example

csharp
Animal[] pets = { new Cat(), new Dog() };
foreach (Animal pet in pets)
{
    pet.Speak();
}

class Animal
{
    public virtual void Speak() => Console.WriteLine("...");
}

class Cat : Animal
{
    public override void Speak() => Console.WriteLine("Meow");
}

class Dog : Animal
{
    public override void Speak() => Console.WriteLine("Woof");
}
Output
Meow
Woof

Each object uses its own version of Speak(). This is called polymorphism.

Start every new class small: a few properties, a constructor and one or two methods. Add more only when your program needs it.

Exercise

Exercise

Which keyword lets a child class replace a virtual method from its parent?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp