Introduction to C#
C# (pronounced "C-Sharp") is a modern, object-oriented, type-safe programming language developed by Microsoft as part of its .NET initiative. It's widely used for developing desktop applications, web applications, games (using Unity), cloud-based software, and more.
Key Features of C#:
- Object-oriented
- Strongly typed
- Component-oriented
- Interoperable with other .NET languages
- Integrated with the .NET framework
C# Basics
Hello World Example
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
This is the most basic example of a C# program. It begins with the using System; directive, which includes the System namespace to access built-in C# functionalities like Console. The Main() method is the entry point of every C# application. Inside it, Console.WriteLine("Hello, World!"); prints the message to the console. This example demonstrates the syntax structure, method declaration, and how to output text in C#.
Structure of a C# Program
- using System; - Includes the System namespace
- class Program - Defines a class
- static void Main() - Entry point of the program
A typical C# program starts with a using directive to include namespaces like System, which provides access to essential classes such as Console. The program is encapsulated within a class—commonly named Program. The Main() method is the entry point of execution, and it's marked as static since it's called by the runtime without creating an instance of the class. This structure forms the foundation of all C# applications.
Variables and Data Types
Declaration
int age = 25;
string name = "Waleed";
double salary = 50000.50;
bool isActive = true;
char grade = 'A';
Common Data Types
- int - Integer
- double, float - Decimal numbers
- char - Single character
- string - Text
- bool - Boolean
- var - Automatically infers type
In C#, variables must be declared with a specific data type, which determines the kind of data they can store. Common data types include int for whole numbers, double and float for decimal values, char for single characters, string for text, and bool for true/false values. The var keyword allows the compiler to infer the data type automatically based on the assigned value. Using the correct data type helps in optimizing memory and ensuring type safety.
Operators
int a = 10, b = 5;
int sum = a + b; // Arithmetic
bool isEqual = a == b; // Comparison
bool logic = a > 5 && b < 10; // Logical
C# provides a variety of operators to perform different operations. Arithmetic operators like +, -, *, /, and % are used for mathematical calculations. Comparison operators such as ==, !=, >, <, >=, and <= are used to compare values. Logical operators like && (AND), || (OR), and ! (NOT) help in making complex logical decisions based on multiple conditions.
Control Statements
If Statement
int age = 25;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
Control statements in C# are used to make decisions and execute specific blocks of code based on certain conditions. The if statement evaluates a condition and runs the code inside the block if the condition is true. It helps in controlling the flow of execution in a program.
If-else Statement
using System;
class Program
{
static void Main()
{
int age = 17;
if (age >= 18)
{
Console.WriteLine("You are eligible to vote.");
}
else
{
Console.WriteLine("You are not eligible to vote.");
}
}
}
The if-else statement in C# is used when you want to execute one block of code if a condition is true and a different block if the condition is false. It provides a way to handle two possible outcomes in decision-making scenarios.
If-else if Statement
int score = 70;
if (score >= 90)
Console.WriteLine("Excellent");
else if (score >= 50)
Console.WriteLine("Good");
else
Console.WriteLine("Try again");
The if-else if statement allows multiple conditions to be checked in sequence. It executes the first true condition and ignores the rest. This is useful when you have more than two possible outcomes based on different conditions.
Switch Statement
int day = 2;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
default:
Console.WriteLine("Other day");
break;
}
The switch statement is used to select one of many blocks of code to be executed based on the value of a variable or expression. It provides a cleaner alternative to multiple if-else statements when dealing with fixed values like days of the week or menu options.
Loops
For Loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
The for loop in C# is used for executing a block of code a specific number of times. It includes an initializer, a condition, and an increment/decrement expression, making it ideal for counted loops.
While Loop
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
The while loop continues to execute a block of code as long as the specified condition is true. It's typically used when the number of iterations is not known beforehand.
Do-While Loop
int i = 0;
do
{
Console.WriteLine(i);
i++;
} while (i < 5);
The do-while loop executes the block of code at least once before checking the condition. It then continues to loop as long as the condition remains true.
Arrays in C#
int[] numbers = {1, 2, 3, 4, 5};
Console.WriteLine(numbers[2]); // Output: 3
Arrays in C# are used to store multiple values of the same type in a single variable. Each element in the array is accessed using an index, starting from 0.
Multi-dimensional Array
int[,] matrix = {
{1, 2},
{3, 4}
};
A multi-dimensional array in C# is used to represent data in a tabular form, such as a matrix. It allows storing values in rows and columns using multiple indices.
Methods (Functions)
Method Declaration
static void Greet(string name)
{
Console.WriteLine("Hello " + name);
}
Greet("Waleed");
Return Values
static int Add(int a, int b)
{
return a + b;
}
Methods in C# are blocks of code that perform specific tasks and can be reused. They help organize code into logical sections, improve readability, and support parameters and return values for flexible operations.
Object-Oriented Programming (OOP)
Class and Object
class Person
{
public string name;
public void Speak()
{
Console.WriteLine("Hi, I'm " + name);
}
}
Person p = new Person();
p.name = "Waleed";
p.Speak();
Object-Oriented Programming (OOP) in C# is based on the concept of classes and objects. A class is a blueprint for creating objects, which are instances of that class. This approach promotes modular, reusable, and organized code.
Constructor
class Car
{
public string model;
public Car(string modelName)
{
model = modelName;
}
}
A constructor is a special method in a class that is automatically invoked when an object is created. It is used to initialize objects with default or specific values. In C#, constructors have the same name as the class and do not have a return type.
Inheritance
class Animal
{
public void Eat() { Console.WriteLine("Eating..."); }
}
class Dog : Animal
{
public void Bark() { Console.WriteLine("Barking..."); }
}
Inheritance allows a class (called the derived or child class) to inherit fields and methods from another class (called the base or parent class). It promotes code reusability and establishes a relationship between classes. In C#, inheritance is implemented using the : symbol.
Polymorphism
Method Overloading
class MathOps
{
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;
}
Method Overriding
class Base
{
public virtual void Show() => Console.WriteLine("Base");
}
class Derived : Base
{
public override void Show() => Console.WriteLine("Derived");
}
Polymorphism allows methods to behave differently based on the context. In C#, it is achieved through method overloading (same method name with different parameters) and method overriding (derived class provides a specific implementation of a method defined in the base class). It enhances flexibility and maintainability in object-oriented programming.
Encapsulation
class BankAccount
{
private double balance;
public void Deposit(double amount)
{
if (amount > 0)
balance += amount;
}
public double GetBalance()
{
return balance;
}
}
Encapsulation is the concept of wrapping data and the methods that operate on that data into a single unit, typically a class. It restricts direct access to some of an object's components, which is done by using access modifiers like private and providing public methods (getters/setters) to access or modify them. This helps protect the internal state of the object and promotes maintainability and security.
Abstraction
abstract class Animal
{
public abstract void Sound();
}
class Cat : Animal
{
public override void Sound()
{
Console.WriteLine("Meow");
}
}
Abstraction is a fundamental principle of object-oriented programming that allows you to define abstract classes and methods, focusing on what an object does instead of how it does it. In C#, abstraction is achieved using the abstract keyword. An abstract class cannot be instantiated directly and may contain abstract methods without implementation, which must be implemented by derived classes. This helps in designing flexible and scalable applications by hiding complex implementation details.
Exception Handling
try
{
int result = 10 / 0;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error: " + e.Message);
}
finally
{
Console.WriteLine("Always runs");
}
Exception handling in C# is used to manage runtime errors gracefully and maintain normal application flow. The try block contains the code that may cause an exception. If an error occurs, the catch block handles the exception, allowing the program to continue running instead of crashing. The finally block contains code that executes regardless of whether an exception was thrown or not-commonly used for cleanup operations like closing files or releasing resources.
Namespaces
namespace MyApp
{
class Test
{
public void Print() => Console.WriteLine("Inside Namespace");
}
}
Namespaces in C# are used to organize code and avoid naming conflicts. They act as containers for classes, interfaces, structs, and other types, allowing developers to group related functionality together. Using namespaces also enables better modularity and maintainability of code, especially in large applications. You can access members of a namespace using the dot (.) operator or by importing the namespace with the using keyword.
File Handling
using System.IO;
File.WriteAllText("file.txt", "Hello File");
string content = File.ReadAllText("file.txt");
Console.WriteLine(content);
File handling in C# is performed using classes in the System.IO namespace. It allows reading from and writing to files on the system. Methods like File.WriteAllText and File.ReadAllText simplify the process of writing a string to a file and reading the content back. Proper file handling is essential for tasks such as data storage, configuration management, and logging in applications.
C# and Databases
SQL Connection Example (using ADO.NET)
using System.Data.SqlClient;
SqlConnection con = new SqlConnection("your_connection_string");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Users", con);
SqlDataReader reader = cmd.ExecuteReader();
C# interacts with databases using ADO.NET, a part of the .NET framework. It provides classes like SqlConnection, SqlCommand, and SqlDataReader to establish connections, execute SQL queries, and read data. This enables developers to perform operations like reading, inserting, updating, and deleting records directly from C# applications.
C# in Game Development
- Unity uses C# as its primary scripting language.
- Used to create 2D/3D games, physics simulations, VR, etc.
void Update()
{
transform.Translate(Vector3.forward * Time.deltaTime);
}
C# is widely used in game development, especially with the Unity game engine. Unity leverages C# for scripting behaviors, controlling game objects, handling physics, managing input, and creating complex gameplay mechanics. It enables rapid prototyping and efficient game logic implementation for both 2D and 3D games.
Advanced Concepts
- Delegates
- Events
- Lambda Expressions
- LINQ (Language Integrated Query)
- Asynchronous Programming with async and await
- Generics
C# offers several advanced features that enhance code flexibility, readability, and performance. Delegates and events support robust event-driven programming. Lambda expressions provide concise syntax for writing anonymous functions. LINQ enables powerful, readable data querying directly within C#. Asynchronous programming with async and await improves responsiveness by handling tasks concurrently. Generics allow for type-safe, reusable code structures.
Tools & Frameworks
- Visual Studio / Visual Studio Code
- .NET SDK
- ASP.NET for Web Applications
- Xamarin for Mobile Apps
- Entity Framework for ORM
C# development is supported by a rich ecosystem of tools and frameworks. Visual Studio and Visual Studio Code provide powerful IDEs for coding, debugging, and managing projects. The .NET SDK enables building, running, and publishing applications. ASP.NET is used for building dynamic web applications, while Xamarin allows cross-platform mobile app development. Entity Framework simplifies database operations through Object-Relational Mapping (ORM).
Practice Projects
- Calculator App
- Student Record System
- To-Do List
- Bank Management System
- Login/Signup Form
- Simple Blog using ASP.NET
- Tic-Tac-Toe Game
Click here for online C# Code reader.
Click here to download VS Code.
Click to go back Home.