Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

C# Comprehensive Tutorial

Introduction to C#

C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of its .NET initiative. It is designed to be simple, yet powerful, and is widely used for developing desktop applications, web applications, and games using the Unity game engine.

Getting Started with C#

Before you start writing C# code, you need to have the .NET framework and an Integrated Development Environment (IDE) like Visual Studio installed on your machine. You can download Visual Studio from the official Visual Studio website.

Once you have Visual Studio installed, you can create a new C# project by following these steps:

  1. Open Visual Studio.
  2. Click on "Create a new project".
  3. Select "Console App (.NET Core)" and click "Next".
  4. Enter the project name and location, then click "Create".

Basic Syntax

Let's start with a simple "Hello, World!" program to understand the basic syntax of C#.

using System;

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

Explanation:

  • using System;: This line imports the System namespace, which contains fundamental classes for basic operations.
  • namespace HelloWorld: Namespaces are used to organize code into a logical hierarchy.
  • class Program: This defines a class named Program.
  • static void Main(string[] args): The Main method is the entry point of a C# application.
  • Console.WriteLine("Hello, World!");: This line prints "Hello, World!" to the console.

Data Types

C# is a strongly typed language, meaning every variable must have a type. Here are some common data types:

  • int: Represents an integer.
  • double: Represents a double-precision floating point number.
  • char: Represents a single character.
  • string: Represents a sequence of characters.
  • bool: Represents a boolean value (true or false).

Example:

int age = 25;
double height = 5.9;
char grade = 'A';
string name = "John";
bool isStudent = true;
                

Control Structures

Control structures are used to change the flow of execution of a program. The most common control structures are if-else statements, loops (for, while, do-while), and switch statements.

If-Else Statement

Example:

int number = 10;

if (number > 0)
{
    Console.WriteLine("Positive number");
}
else
{
    Console.WriteLine("Negative number");
}
                

For Loop

Example:

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

While Loop

Example:

int i = 0;

while (i < 5)
{
    Console.WriteLine("Value of i: " + i);
    i++;
}
                

Switch Statement

Example:

int day = 3;

switch (day)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Other day");
        break;
}
                

Object-Oriented Programming

C# is an object-oriented programming language, which means it supports the principles of object-oriented programming (OOP) such as encapsulation, inheritance, and polymorphism.

Classes and Objects

A class is a blueprint for objects. An object is an instance of a class.

Example:

public class Car
{
    public string color;
    public int speed;

    public void Drive()
    {
        Console.WriteLine("The car is driving at " + speed + " km/h.");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car myCar = new Car();
        myCar.color = "Red";
        myCar.speed = 100;
        myCar.Drive();
    }
}
                

Inheritance

Inheritance allows a class to inherit properties and methods from another class.

Example:

public class Animal
{
    public void Eat()
    {
        Console.WriteLine("Eating...");
    }
}

public class Dog : Animal
{
    public void Bark()
    {
        Console.WriteLine("Barking...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dog myDog = new Dog();
        myDog.Eat();
        myDog.Bark();
    }
}
                

Polymorphism

Polymorphism allows methods to do different things based on the object it is acting upon.

Example:

public class Animal
{
    public virtual void MakeSound()
    {
        Console.WriteLine("Animal sound");
    }
}

public class Dog : Animal
{
    public override void MakeSound()
    {
        Console.WriteLine("Bark");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Animal myDog = new Dog();
        myDog.MakeSound();
    }
}
                

Integrating C# with Kafka

Apache Kafka is a distributed streaming platform. You can use Kafka to build real-time streaming data pipelines and applications. In this section, we will show how to integrate C# with Kafka.

Setting Up Kafka

Before integrating Kafka with C#, you need to have Kafka installed and running on your machine. You can download Kafka from the official Kafka website and follow the installation instructions.

Installing Confluent.Kafka

We will use the Confluent.Kafka library to integrate Kafka with C#. To install the library, open the NuGet Package Manager Console in Visual Studio and run the following command:

Install-Package Confluent.Kafka

Producing Messages

Example:

using System;
using Confluent.Kafka;

class Producer
{
    public static void Main(string[] args)
    {
        var config = new ProducerConfig { BootstrapServers = "localhost:9092" };

        using (var producer = new ProducerBuilder(config).Build())
        {
            for (int i = 0; i < 5; i++)
            {
                var result = producer.ProduceAsync("test-topic", new Message { Value = $"Message {i}" }).Result;
                Console.WriteLine($"Delivered '{result.Value}' to '{result.TopicPartitionOffset}'");
            }

            producer.Flush(TimeSpan.FromSeconds(10));
        }
    }
}
                

Consuming Messages

Example:

using System;
using Confluent.Kafka;

class Consumer
{
    public static void Main(string[] args)
    {
        var config = new ConsumerConfig
        {
            GroupId = "test-consumer-group",
            BootstrapServers = "localhost:9092",
            AutoOffsetReset = AutoOffsetReset.Earliest
        };

        using (var consumer = new ConsumerBuilder(config).Build())
        {
            consumer.Subscribe("test-topic");

            while (true)
            {
                var consumeResult = consumer.Consume();
                Console.WriteLine($"Consumed message '{consumeResult.Value}' at: '{consumeResult.TopicPartitionOffset}'.");
            }
        }
    }
}