Introduction to C#

C# (pronounced "C-sharp") is a modern, object-oriented, and type-safe programming language developed by Microsoft. It is a versatile language that can be used to build a wide range of applications, from web services and desktop applications to mobile apps and games.

This document provides a foundational overview of the core concepts of the C# language. Understanding these basics is crucial for anyone looking to start programming with C#.

Variables and Data Types

Variables are named storage locations that hold data values. In C#, variables must be declared with a specific data type before they can be used.

Common Data Types

  • int: For whole numbers (e.g., 10, -5).
  • double: For floating-point numbers (e.g., 3.14, -0.5).
  • bool: For true or false values.
  • char: For single characters (e.g., 'A', '$').
  • string: For sequences of characters (e.g., "Hello, World!").
  • object: The ultimate base type for all types in C#.

Variable Declaration and Initialization


int age = 30;
string name = "Alice";
double price = 19.99;
bool isActive = true;
                

Operators

Operators are symbols that perform operations on variables and values.

Arithmetic Operators

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulus (remainder of division)

Comparison Operators

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

Logical Operators

  • &&: Logical AND
  • ||: Logical OR
  • !: Logical NOT

Control Flow Statements

Control flow statements determine the order in which code is executed.

Conditional Statements


if (score > 90)
{
    Console.WriteLine("Excellent!");
}
else if (score > 70)
{
    Console.WriteLine("Good job.");
}
else
{
    Console.WriteLine("Keep practicing.");
}

// Using the switch statement
int dayOfWeek = 3;
switch (dayOfWeek)
{
    case 1:
        Console.WriteLine("Monday");
        break;
    case 2:
        Console.WriteLine("Tuesday");
        break;
    case 3:
        Console.WriteLine("Wednesday");
        break;
    default:
        Console.WriteLine("Another day.");
        break;
}
                

Looping Statements


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

// While loop
int count = 0;
while (count < 3)
{
    Console.WriteLine($"Count: {count}");
    count++;
}

// Foreach loop (for collections)
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}
                

Methods (Functions)

Methods are blocks of code that perform a specific task. They help in organizing code and promoting reusability.


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

// Calling the method
int sum = Add(5, 3); // sum will be 8
Console.WriteLine($"The sum is: {sum}");
                

Classes and Objects

C# is an object-oriented programming language. Classes are blueprints for creating objects, which are instances of those classes.


// Class definition
public class Person
{
    public string Name;
    public int Age;

    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
    }
}

// Creating an object (instance of the Person class)
Person person1 = new Person();
person1.Name = "Bob";
person1.Age = 25;

// Calling a method on the object
person1.Greet(); // Output: Hello, my name is Bob and I am 25 years old.
                

Namespaces

Namespaces are used to organize code and prevent naming conflicts. The using directive allows you to access types defined in a namespace.


using System; // Accesses types like Console

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello from C#!");
    }
}
                

Error Handling

Exception handling is a mechanism to deal with runtime errors. The try-catch block is commonly used.


try
{
    int result = 10 / 0; // This will cause a DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
catch (Exception ex)
{
    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
finally
{
    Console.WriteLine("This block always executes.");
}
                

Next Steps

This document has covered the very basics of C#. To further your learning, you should explore topics such as:

  • Data structures (Arrays, Lists, Dictionaries)
  • Object-Oriented Programming concepts (Inheritance, Polymorphism, Encapsulation)
  • LINQ (Language Integrated Query)
  • Asynchronous programming
  • Working with files and I/O
  • Web development with ASP.NET Core
  • Game development with Unity

Continue exploring the MSDN documentation for in-depth guides and tutorials on these and many other C# features.