UmbrellaCrow612 / code-handbook

Code Handbook, a comprehensive repository that serves as your go-to guide for all things coding. Whether you're a beginner or an experienced developer, this repository is designed to provide you with a wealth of knowledge, resources, and practical examples to enhance your coding skills.
https://code-handbook.vercel.app
MIT License
3 stars 0 forks source link

Classes in c# #63

Open UmbrellaCrow612 opened 1 year ago

UmbrellaCrow612 commented 1 year ago

Learning C# Classes

In C#, classes are fundamental to object-oriented programming (OOP). They are blueprints for creating objects, which are instances of a class. In this guide, we will cover the concepts of classes, their uses, and provide examples to help you understand them better.


1. What are Classes?

A class is a blueprint for creating objects. It defines the structure and behavior of objects of that class. Think of a class as a template that describes how an object should be created and what it can do.

2. Creating a Class

To create a class in C#, you use the class keyword followed by the class name. Here's a basic example:

public class Person
{
    // Class members go here
}

3. Class Members

Classes can contain various members that define their properties and behavior.

Fields

Fields are variables that store data within a class. They represent the state of an object. Example:

public class Person
{
    public string Name; // Field
}

Properties

Properties are used to get or set the values of fields. They provide controlled access to the class's data. Example:

public class Person
{
    public string Name { get; set; } // Property
}

Methods

Methods are functions defined within a class. They perform actions or provide functionality. Example:

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }
}

4. Constructors

Constructors are special methods used to initialize objects of a class. They have the same name as the class and are called when an object is created. Example:

public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }
}

5. Inheritance

Inheritance allows you to create a new class based on an existing class, inheriting its members. It promotes code reuse and supports the "is-a" relationship. Example:

public class Student : Person
{
    public int StudentId { get; set; }
}

6. Examples

Let's put it all together with some examples:

public class Person
{
    public string Name { get; set; }

    public Person(string name)
    {
        Name = name;
    }

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name}.");
    }
}

public class Student : Person
{
    public int StudentId { get; set; }

    public Student(string name, int studentId) : base(name)
    {
        StudentId = studentId;
    }
}

In this example, we have a Person class with a constructor and a Greet method. The Student class inherits from Person and adds a StudentId property and its constructor.

7. Access Modifiers

Access modifiers control the visibility and accessibility of class members. The common access modifiers in C# are:

You can apply access modifiers to fields, properties, methods, and constructors.

8. Static Members

Static members belong to the class itself rather than to instances of the class. They are accessed using the class name, not an instance. Example:

public class MathUtils
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

Usage:

int result = MathUtils.Add(5, 3);

9. Abstract Classes and Methods

An abstract class is a class that cannot be instantiated on its own. It's often used as a base class for other classes and can have abstract methods that must be implemented by derived classes. Example:

public abstract class Shape
{
    public abstract double CalculateArea();
}

public class Circle : Shape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public override double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

10. Sealed Classes

A sealed class is a class that cannot be inherited. It's used when you want to prevent further modification or extension of a class. Example:

public sealed class FinalClass
{
    // Members and methods
}

11. Partial Classes

A partial class allows you to split the definition of a class across multiple files. It's often used in large projects to separate code into manageable sections. Example:

// File 1: MyClassPart1.cs
public partial class MyClass
{
    public void Method1() { }
}

// File 2: MyClassPart2.cs
public partial class MyClass
{
    public void Method2() { }
}

12. Interface

An interface defines a contract that classes can implement. It specifies a set of methods and properties that a class must provide. Here's an example:

public interface IShape
{
    double CalculateArea();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public Circle(double radius)
    {
        Radius = radius;
    }

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

Implementing an interface guarantees that a class will provide specific functionality, promoting consistency in your code.

13. Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common base class. It enables you to write code that works with objects in a more generic way. For example:

public void PrintArea(IShape shape)
{
    Console.WriteLine($"Area: {shape.CalculateArea()}");
}

You can pass any object that implements the IShape interface to this method, demonstrating polymorphism.

14. Method Overloading

Method overloading enables a class to have multiple methods with the same name but different parameters. This allows you to create more flexible and expressive APIs. Example:

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public double Add(double a, double b)
    {
        return a + b;
    }
}

You can call the appropriate Add method based on the data types you provide as arguments.

15. Generics

Generics allow you to create classes, methods, and interfaces with type parameters. This provides greater flexibility and type safety. Example:

public class Stack<T>
{
    private List<T> items = new List<T>();

    public void Push(T item)
    {
        items.Add(item);
    }

    public T Pop()
    {
        if (items.Count == 0)
            throw new InvalidOperationException("Stack is empty");
        T item = items[items.Count - 1];
        items.RemoveAt(items.Count - 1);
        return item;
    }
}

Generics enable you to create data structures and algorithms that work with different data types without sacrificing type safety.

16. Delegates and Events

Delegates and events are used for implementing event-driven programming. Delegates represent methods, and events allow objects to subscribe to and respond to events. Example:

public class Button
{
    public delegate void ClickHandler(object sender, EventArgs e);
    public event ClickHandler Click;

    public void OnClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}

You can use delegates and events to create interactive user interfaces and decouple components in your applications.

17. Extension Methods

Extension methods allow you to add new methods to existing classes without modifying their source code. They are defined in static classes and must have a special parameter called this, indicating the type they extend. Example:

public static class StringExtensions
{
    public static bool IsPalindrome(this string str)
    {
        // Check if the string is a palindrome
    }
}

With extension methods, you can enhance built-in classes or third-party libraries with your custom functionality.

18. LINQ (Language Integrated Query)

LINQ is a powerful feature in C# for querying collections of objects using a SQL-like syntax. It simplifies data manipulation and retrieval. Example:

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers where num % 2 == 0 select num;

LINQ provides a convenient way to work with data, making your code more expressive and readable.

19. Attributes

Attributes are used to add metadata to your code. They provide information to the compiler or runtime about how the code should behave. Example:

[Obsolete("This method is deprecated. Use the newMethod instead.")]
public void OldMethod()
{
    // Code here
}

Attributes are commonly used for documentation, code analysis, and custom behaviors like serialization.

20. Asynchronous Programming

Asynchronous programming in C# allows you to write code that doesn't block the main thread, making your applications more responsive. The async and await keywords simplify working with asynchronous operations. Example:

public async Task<int> DownloadDataAsync()
{
    // Asynchronously download data
    // This method can be awaited in other async methods
}

Asynchronous programming is crucial for handling I/O-bound tasks efficiently.

21. Dependency Injection

Dependency Injection (DI) is a design pattern that promotes loose coupling between components in your code. It allows you to inject dependencies into a class rather than having the class create them. DI frameworks like ASP.NET Core's built-in DI container make this process more manageable. Example:

public class OrderService
{
    private readonly IOrderRepository _repository;

    public OrderService(IOrderRepository repository)
    {
        _repository = repository;
    }

    public void PlaceOrder(Order order)
    {
        _repository.Add(order);
    }
}