;

C# Introduction


C# (pronounced "C-sharp") is a general-purpose, high-level multi-paradigm programming language which is developed by by Microsoft that runs on the .NET Framework. C# encompasses static typing, strong typing, lexically scoped, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines C# widely used for developing web applications, desktop software, mobile apps, games, and more.

The C# programming language was designed by Anders Hejlsberg from Microsoft in 2000 and was later approved as an international standard by Ecma (ECMA-334) in 2002 and ISO/IEC (ISO/IEC 23270) in 2003

This tutorial will introduce you to C# with practical examples and use cases to help you get started.

What is C#?

C# is a statically typed, high-level language that emphasizes simplicity, scalability, and robustness. It is similar to languages like Java and C++, but it integrates more seamlessly with Microsoft technologies. Whether you're building web APIs, cloud-based apps, or games using Unity, C# offers a rich ecosystem to work with.

Key Features of C#

  • Object-Oriented: Everything in C# is organized around objects and classes, making it easier to model real-world systems.
  • Type-Safe: C# ensures that variables are assigned and used in ways that prevent errors at runtime.
  • Automatic Memory Management: The .NET runtime (CLR) manages memory for you, reducing the risk of memory leaks.
  • Rich Standard Library: C# comes with a large library of built-in functions to perform common tasks, speeding up development.
  • Cross-Platform: With .NET Core and .NET 5/6, C# applications can run on Windows, Linux, and macOS.

Setting Up Your Environment

Before writing your first C# program, you need to set up your development environment.

  1. Install Visual Studio: Visual Studio is the most popular Integrated Development Environment (IDE) for C#. Download it from Microsoft’s website. Visual Studio Code is another lightweight option.
  2. Install .NET SDK: To run and compile C# programs, you'll need the .NET SDK. Download it from dotnet.microsoft.com.

Once installed, you can create a new C# project from Visual Studio by selecting the Console App template.

Basic C# Syntax: "Hello, World!" Example

Let’s start with the most basic C# program: printing "Hello, World!" to the console.

Basic C# Syntax: "Hello, World!" Example
using System;
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

Key Components Explained:

  • using System;: Imports the System namespace, which contains basic classes like Console.
  • namespace HelloWorld: A namespace groups related classes. It helps avoid name conflicts.
  • class Program: Defines a class named Program.
  • static void Main(): The entry point of any C# application. Execution starts here.
  • Console.WriteLine(): Prints a message to the console.

Variables and Data Types in C#

In C#, you need to declare variables with a specific data type. C# is a strongly-typed language, which means that you must specify the data type of a variable at the time of declaration.

Common Data Types:

  • int: Represents an integer.
  • double: Represents a double-precision floating-point number.
  • string: Represents a sequence of characters (text).
  • bool: Represents a boolean value (true or false).
Common Data Types
int age = 25;
double salary = 45000.50;
string name = "John";
bool isEmployee = true;

Console.WriteLine($"Name: {name}, Age: {age}, Salary: {salary}, Is Employee: {isEmployee}");

Control Flow Statements

Control flow statements in C# allow you to direct the execution flow based on conditions or repetitions.

If-Else Statement:

int score = 85;

if (score >= 90)
{
    Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
    Console.WriteLine("Grade: B");
}
else
{
    Console.WriteLine("Grade: C");
}

For Loop:

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("Iteration: " + i);
}

While Loop:

int x = 0;
while (x < 5)
{
    Console.WriteLine("Value of x: " + x);
    x++;
}

Switch Case:

string fruit = "apple";

switch (fruit)
{
    case "apple":
        Console.WriteLine("You chose apple.");
        break;
    case "banana":
        Console.WriteLine("You chose banana.");
        break;
    default:
        Console.WriteLine("Unknown fruit.");
        break;
}

Object-Oriented Programming in C#

C# is fully object-oriented, meaning it uses classes and objects to model the real world.

Creating a Class and Object:

class Car
{
    public string Make { get; set; }
    public string Model { get; set; }

    public void DisplayInfo()
    {
        Console.WriteLine($"Make: {Make}, Model: {Model}");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car { Make = "Toyota", Model = "Corolla" };
        myCar.DisplayInfo();
    }
}

In this example, we define a Car class with properties Make and Model. The DisplayInfo method prints the car’s details.

Encapsulation, Inheritance, and Polymorphism:

  • Encapsulation: Wrapping data (fields) and methods in a single unit (class) and restricting access using access modifiers (private, public, protected).
  • Inheritance: Allows one class to inherit members of another class. For example, a Car class could inherit from a more general Vehicle class.
  • Polymorphism: Provides the ability to call the same method on different objects, with each object behaving in its own way.

Exception Handling in C#

C# provides a robust mechanism for handling runtime errors through exceptions. This prevents the program from crashing unexpectedly.

try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]); // This will throw an exception
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Error: " + ex.Message);
}
finally
{
    Console.WriteLine("This block always executes.");
}

The try-catch-finally block helps handle exceptions gracefully.

LINQ: Simplifying Data Queries

LINQ (Language Integrated Query) is a powerful feature in C# that allows you to query collections using SQL-like syntax. Here’s a simple example:

int[] numbers = { 1, 2, 3, 4, 5 };
var evenNumbers = from num in numbers
                  where num % 2 == 0
                  select num;

foreach (var num in evenNumbers)
{
    Console.WriteLine(num);
}

LINQ allows filtering, sorting, and grouping data with minimal code.

Asynchronous Programming with async and await

C# supports asynchronous programming to improve application performance by preventing blocking of the main thread during time-consuming tasks.

static async Task Main()
{
    await GetData();
}

static async Task GetData()
{
    Console.WriteLine("Fetching data...");
    await Task.Delay(2000);  // Simulates a delay
    Console.WriteLine("Data fetched!");
}

This approach is essential for I/O-bound operations like file reading, database access, and network calls.

Summary and Use Cases

C# is a versatile language with a rich set of features that make it suitable for building various types of applications:

  • Web Development: Using ASP.NET Core for building web applications.
  • Desktop Applications: With Windows Forms or WPF for creating GUI-based software.
  • Mobile Apps: Via Xamarin to develop cross-platform mobile applications.
  • Game Development: Unity, a popular game engine, uses C# for scripting.

By mastering C#, you can develop a wide array of applications that run on multiple platforms.