Complete C# Tutorial

C# Classes with Examples - Easy and Friendly Guide for Beginners

👋 Introduction:

Hey there, coding buddy! 👋 Have you ever wondered how you can organize your code when things start getting complicated? That’s where Classes in C# come to the rescue! 🦸‍♀️ Classes help you structure your code, making it neat, reusable, and super easy to manage. Think of them like blueprints for creating objects in your program.

Imagine you’re building a video game. You’ll have players, enemies, and obstacles, right? 🕹️ Each of these can be represented using a class. The class describes what the object is and what it can do. Simple, right? 😎 Don’t worry—we’ll break it down step-by-step with plenty of examples!

📝 What is a Class in C#?

A class is like a blueprint for creating objects. It defines properties (data) and methods (actions) that the objects will have.

💡 Real-world example:

Imagine you’re designing cars in a factory. 🚗 The class is the blueprint (Car), and each car you make is an object created from that blueprint. The blueprint defines that a car has wheels, color, and speed, and actions like drive or stop.

🛠️ Syntax of a Class in C#:

				
					class ClassName  
{  
    // Fields (Variables)  
    // Methods (Functions)  
}
				
			

🔑 Explanation:

  • class ClassName: Defines a class with the name ClassName.
  • Inside the class, you define variables (fields) and functions (methods) to describe the object’s behavior and attributes.

🖥️ Simple Program to Demonstrate Classes in C#:

Let’s create a simple Car class and see how it works! 🚗

				
					using System;

class Car  
{
    public string color;  // Field  
    public void Drive()   // Method  
    {
        Console.WriteLine("The car is driving.");  
    }
}

class Program  
{
    static void Main()  
    {
        Car myCar = new Car();     // Creating an object of Car  
        myCar.color = "Red";       // Setting the color  
        Console.WriteLine("Car color: " + myCar.color);  
        myCar.Drive();             // Calling the method  
    }
}
				
			

🖨️ Output:

				
					Car color: Red  
The car is driving.  
				
			

🔍 Code Explanation:

  • We created a class named Car with a field color and a method Drive().
  • Inside Main(), we created an object myCar from the Car class.
  • We set the color field to "Red" and called the Drive() method.
  • The output shows the car’s color and that it’s driving. 🚗💨

🌍 Real-World Scenario Example:

Let’s say you’re running a school management system. 🏫 You need to represent students with their names and ages. Sounds like a perfect job for classes!

				
					using System;

class Student  
{
    public string name;  
    public int age;  

    public void DisplayInfo()  
    {
        Console.WriteLine($"Name: {name}, Age: {age}");  
    }
}

class Program  
{
    static void Main()  
    {
        Student student1 = new Student();  
        student1.name = "Steven";  
        student1.age = 20;  
        student1.DisplayInfo();  

        Student student2 = new Student();  
        student2.name = "Emma";  
        student2.age = 22;  
        student2.DisplayInfo();  
    }
}
				
			

🖨️ Output:

				
					Name: Steven, Age: 20  
Name: Emma, Age: 22  
				
			

🔍 Code Explanation:

  • We created a Student class with name and age fields and a method DisplayInfo().
  • In Main(), we created two student objects, assigned values, and displayed their information. 🎓
  • This example shows how you can easily manage data for multiple students using classes.

🧩 Different Types of Classes in C#:

C# offers various types of classes to handle different scenarios. Let’s explore some of them with examples! 🌟

1️⃣ Static Class:

A static class can’t be instantiated. You can only call its static members.

				
					using System;

static class MathHelper  
{
    public static int Add(int a, int b) => a + b;  
}

class Program  
{
    static void Main()  
    {
        int result = MathHelper.Add(5, 3);  
        Console.WriteLine($"Sum: {result}");  
    }
}
				
			

🖨️ Output:

				
					Sum: 8  
				
			

👉 Why use it?
Use static classes when you need utility functions like calculations or helper methods.

2️⃣ Partial Class:

Breaks a class into multiple files, making large classes manageable.

				
					// File: PersonPart1.cs
public partial class Person  
{
    public string FirstName;  
}

// File: PersonPart2.cs
public partial class Person  
{
    public string LastName;  

    public void DisplayFullName()  
    {
        Console.WriteLine($"Full Name: {FirstName} {LastName}");  
    }
}

// Main Program
class Program  
{
    static void Main()  
    {
        Person person = new Person { FirstName = "Steven", LastName = "Smith" };  
        person.DisplayFullName();  
    }
}
				
			

🖨️ Output:

				
					Full Name: Steven Smith  
				
			

👉 Why use it?
Great for teamwork where multiple developers work on the same class! 👥

3️⃣ Nested Class:

A class inside another class. Useful for closely related functionalities.

				
					using System;

class Outer  
{
    public class Inner  
    {
        public void Show() => Console.WriteLine("Hello from Inner Class!");  
    }
}

class Program  
{
    static void Main()  
    {
        Outer.Inner inner = new Outer.Inner();  
        inner.Show();  
    }
}
				
			

🖨️ Output:

				
					Hello from Inner Class!  
				
			

👉 Why use it?
Helps in logically grouping classes that are only used in one place.

4️⃣ Abstract Class:

Can’t be instantiated. Designed to be a base class for other classes.

				
					using System;

abstract class Shape  
{
    public abstract void Draw();  
}

class Circle : Shape  
{
    public override void Draw() => Console.WriteLine("Drawing Circle.");  
}

class Program  
{
    static void Main()  
    {
        Shape shape = new Circle();  
        shape.Draw();  
    }
}
				
			

🖨️ Output:

				
					Drawing Circle.  
				
			

👉 Why use it?
Perfect for defining a base template that other classes can extend.

5️⃣ Sealed Class:

Prevents other classes from inheriting from it.

				
					using System;

sealed class Calculator  
{
    public int Multiply(int a, int b) => a * b;  
}

class Program  
{
    static void Main()  
    {
        Calculator calc = new Calculator();  
        Console.WriteLine($"Product: {calc.Multiply(4, 5)}");  
    }
}
				
			

🖨️ Output:

				
					Product: 20  
				
			

👉 Why use it?
Use when you want to restrict inheritance for safety or design reasons.

🏁 Conclusion:

Woohoo! 🎉 You’ve just explored different types of Classes in C# and how they work with real-world examples. Classes make coding so much easier and organized. 💡 With this knowledge, you can handle complex projects with ease. So, keep experimenting and stay curious! 🚀

📅 Next What?

Awesome job! 🎉 You’ve just finished learning about Classes in C#. Feeling more confident? I bet you are! 😎

Next up, we’re diving into Objects in C#. You’ll discover how to create, use, and play around with objects—because what’s a class without its object buddies? 😉 Get ready for some fun and interactive examples!

Leave a Comment

Share this Doc

Classes in C#

Or copy link