C# Tutorial

Introduction to C#

C# is a modern, object-oriented programming language developed by Microsoft as part of the .NET initiative. Its syntax is similar to C++ and Java, making it easy for developers familiar with those languages to learn. C# is designed to be simple, type-safe, and highly versatile, allowing it to be used in various applications, from web and desktop applications to mobile development and cloud computing.

Key Features of C#

1. Object-Oriented Programming (OOP): C# is an object-oriented language, meaning it supports principles such as inheritance, polymorphism, encapsulation, and abstraction. This design promotes modular code, making it easier to manage and scale complex applications.

2. Type Safety: C# enforces strong typing, which helps reduce errors by ensuring variables are used consistently and correctly.

3. Memory Management with Garbage Collection: C# uses an automatic garbage collector to manage memory allocation and release, reducing the need for manual memory management and minimizing memory leaks.

4. Cross-Platform Support with .NET Core: With .NET Core, C# applications can run on Windows, macOS, and Linux, making it a flexible choice for cross-platform development.

5. Unified Language Features: C# integrates features from procedural, functional, and object-oriented programming paradigms, making it adaptable for a wide range of programming tasks.

6. Asynchronous Programming: C# supports asynchronous programming with async and await keywords, simplifying the development of applications that handle multiple tasks simultaneously, such as web applications.

Basic Structure of a C# Program

A basic C# program consists of a Main method, which is the entry point of the application. Here’s a simple example:

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Output:
Hello, World!

Explanation
1. using System; - Imports the System namespace, which provides fundamental classes and base classes (e.g., Console).

2. namespace HelloWorld - Defines a namespace called HelloWorld to organize classes. A namespace is a container for classes and other namespaces.

3. class Program - Declares a class named Program. In C#, all code must be inside a class or struct.

4. static void Main(string[] args) - The Main method is the entry point of a C# application. It must be static, meaning it belongs to the class itself rather than any instance of the class.

5. Console.WriteLine("Hello, World!"); - Calls the WriteLine method from the Console class to display a message on the screen.

Data Types in C#

C# provides several data types for handling various types of data, grouped into value types and reference types.

1. Value Types: Store data directly. Examples include int, double, bool, char, and float.

2. Reference Types: Store references to data. Examples include string, object, and arrays.

Examples:
int age = 25;
double salary = 50000.75;
bool isEmployed = true;
char grade = 'A';
string name = "John Doe";

Common C# Data Types

TypeSizeDescription
int4 bytesWhole numbers (e.g., -2,147,483,648 to 2,147,483,647)
double8 bytesDouble-precision floating-point numbers
bool1 byteBoolean values (true or false)
char2 bytesSingle Unicode character
stringVariableSequence of characters

Control Flow in C#

C# supports conditional statements and loops, including if, else, switch, for, foreach, while, and do-while.

Example of if-else statement:

int number = 10;
if (number > 0)
{
    Console.WriteLine("The number is positive.");
}
else
{
    Console.WriteLine("The number is negative or zero.");
}

Output:
The number is positive.


Explanation
The program checks if the value of number is greater than zero. If it is, it displays "The number is positive." Otherwise, it displays "The number is negative or zero."

Example of a for loop:
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine("Count: " + i);
}

Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5


Explanation
The for loop iterates from i = 1 to i = 5, printing the current count at each step.

Classes and Objects

Classes are blueprints for creating objects in C#. An object is an instance of a class that contains data and behaviors defined by the class.

Example of a Class and Object:
class Car
{
    public string color;
    public string model;

    public void DisplayDetails()
    {
        Console.WriteLine("Car Model: " + model + ", Color: " + color);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.color = "Red";
        myCar.model = "Toyota";

        myCar.DisplayDetails();
    }
}

Output:
Car Model: Toyota, Color: Red

Explanation
1. Class Definition (Car) - The Car class has two fields, color and model, and a method DisplayDetails that prints the details of the car.

2. Object Creation (myCar) - The myCar object is an instance of the Car class, allowing access to Car fields and methods.

3. Setting Field Values - myCar.color and myCar.model are assigned values.

4. Calling Method - myCar.DisplayDetails() displays the car details.

Conclusion

C# is a robust and versatile language with a strong emphasis on simplicity, performance, and scalability. Its vast library and integrated development environment support make it an excellent choice for both beginners and experienced developers.

Next: C# Development Environment

>