Chapter 3 Introduction to C#

Introduction to C#

C# (pronounced C-sharp) is a popular, modern programming language developed by Microsoft. It’s widely used for developing Windows applications, web applications, games, and mobile apps. Whether you’re new to programming or have some experience, learning C# opens doors to a world of possibilities. This blog post will guide you through the fundamentals of C#, covering everything from data types to object-oriented concepts.

3.1 Language Fundamentals

To get started with C#, it’s essential to understand its basic building blocks. These are the foundation of C# programming and help you write efficient, functional code.

3.1.1 Data Types and Control Constructs

In C#, data types define what kind of value a variable can hold. The language supports several built-in data types:

  • Value Types: These include simple types like int (for integers), float (for floating-point numbers), and bool (for Boolean values).
  • Reference Types: These include more complex data structures like classes, arrays, and strings.

Control constructs in C# determine the flow of execution in your program. They include:

  • If-else: Makes decisions based on conditions.
  • Switch-case: Allows selection from multiple options.
  • Loops: Such as for, while, and do-while, which repeat a block of code until a condition is met.

3.1.2 Value and Reference Types, Boxing

In C#, types are divided into Value Types and Reference Types.

  • Value Types: Store the actual data (e.g., integers, floats, and structs). When you assign a value type variable to another, the value is copied.
  • Reference Types: Store a reference (or memory address) to the data (e.g., classes, arrays, strings). Assigning a reference type variable to another doesn’t copy the data, but rather points to the same data location.

Boxing is the process of converting a value type to a reference type, like wrapping a value type in an object. While useful, boxing can lead to performance overhead if not handled carefully.

3.1.3 Arrays

An array in C# is a collection of values of the same data type. Arrays help store and manage large sets of data efficiently. For example, you can store multiple integers in an array like this:

int[] numbers = { 1, 2, 3, 4, 5 };

Arrays have a fixed size, and their elements can be accessed using an index (starting at 0).

3.1.4 String Class and Its Various Operations

In C#, strings are objects of the String class, which provides a wide range of built-in methods for working with text. Some useful string operations include:

  • Concatenation: Combining multiple strings using the + operator or String.Concat() method.
  • Substring: Extracting a portion of a string with the Substring() method.
  • Length: Finding the number of characters in a string using the Length property.

Strings are immutable in C#, meaning once a string is created, it cannot be changed. Operations on strings create new strings instead of modifying the original.

3.1.5 Functions

Functions (also known as methods in C#) are blocks of reusable code that perform specific tasks. A function can take inputs (parameters), perform an operation, and return a result. Here’s a simple example of a function that adds two numbers:

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

Functions make your code modular, readable, and easier to maintain.

3.2 Object-Oriented Concepts

C# is an object-oriented programming (OOP) language, meaning it allows you to design programs around objects that represent real-world entities. Let’s explore the core OOP concepts in C#.

3.2.1 Defining Classes and Objects

A class is a blueprint for creating objects. It defines properties (attributes) and methods (actions) that objects of that class will have. An object is an instance of a class.

class Car
{
    public string Make;
    public string Model;

    public void Start()
    {
        Console.WriteLine("The car is starting.");
    }
}

Here, Car is a class, and you can create objects of the Car class to represent individual cars.

3.2.2 Access Modifiers

Access modifiers control the visibility of class members (variables and methods). The most common access modifiers are:

  • Public: Accessible from anywhere.
  • Private: Accessible only within the same class.
  • Protected: Accessible within the class and its derived classes.
  • Internal: Accessible within the same assembly.

These modifiers help control the level of access and protect data from unwanted changes.

3.2.3 Constructors

A constructor is a special method used to initialize objects when they are created. It’s called automatically when an object is instantiated. Constructors have the same name as the class and can have parameters to pass initial values.

class Car
{
    public string Make;
    public string Model;

    public Car(string make, string model)
    {
        Make = make;
        Model = model;
    }
}

Here, the constructor initializes the Make and Model properties of a Car object.

3.2.4 Inheritance

Inheritance allows one class to inherit properties and methods from another. This helps in reusing code and establishing relationships between classes. For example:

class Vehicle
{
    public void Move() { Console.WriteLine("The vehicle is moving."); }
}

class Car : Vehicle
{
    public void Start() { Console.WriteLine("The car is starting."); }
}

In this case, Car inherits from Vehicle, so it can use the Move() method of the parent class.

3.2.5 Interface

An interface defines a contract that classes must follow. It contains method signatures but no implementation. A class that implements an interface must provide the implementation for all its methods.

interface IDriveable
{
    void Drive();
}

class Car : IDriveable
{
    public void Drive()
    {
        Console.WriteLine("Driving the car.");
    }
}

Interfaces are useful for defining common behaviors across different classes.

3.2.6 Abstract Class

An abstract class is a class that cannot be instantiated directly. It can contain both abstract methods (without implementation) and regular methods (with implementation). Derived classes must implement the abstract methods.

abstract class Animal
{
    public abstract void Speak();
}

class Dog : Animal
{
    public override void Speak() { Console.WriteLine("Woof!"); }
}

Abstract classes are helpful when you want to provide a common base class with some default behavior but also require specific implementations in derived classes.

3.2.7 Method Overloading and Overriding

  • Method Overloading: Allows you to define multiple methods with the same name but different parameters.
class Calculator
{
    public int Add(int a, int b) { return a + b; }
    public double Add(double a, double b) { return a + b; }
}
  • Method Overriding: Allows a derived class to provide its own implementation of a method defined in the base class.
class Animal
{
    public virtual void Speak() { Console.WriteLine("Animal speaks"); }
}

class Dog : Animal
{
    public override void Speak() { Console.WriteLine("Woof!"); }
}

3.2.8 Delegates

A delegate is a type that represents a reference to a method. It allows methods to be passed as parameters, enabling event-driven programming and callback mechanisms.

delegate void GreetDelegate(string name);

class Program
{
    static void Greet(string name) { Console.WriteLine($"Hello, {name}!"); }

    static void Main()
    {
        GreetDelegate greet = new GreetDelegate(Greet);
        greet("John");
    }
}

Delegates are particularly useful in scenarios like event handling.

Conclusion

C# is a powerful, versatile language that supports both procedural and object-oriented programming. Understanding its fundamental concepts—such as data types, control constructs, and object-oriented principles—will help you build a solid foundation in C#. With this knowledge, you can start creating efficient, scalable, and maintainable applications. Keep exploring and practicing to become proficient in C# programming!

Scroll to Top