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.
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.
Before writing your first C# program, you need to set up your development environment.
Once installed, you can create a new C# project from Visual Studio by selecting the Console App template.
Let’s start with the most basic C# program: printing "Hello, World!" to the console.
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
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.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.
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 in C# allow you to direct the execution flow based on conditions or repetitions.
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else
{
Console.WriteLine("Grade: C");
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
int x = 0;
while (x < 5)
{
Console.WriteLine("Value of x: " + x);
x++;
}
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;
}
C# is fully object-oriented, meaning it uses classes and objects to model the real world.
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.
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 (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.
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.
C# is a versatile language with a rich set of features that make it suitable for building various types of applications:
By mastering C#, you can develop a wide array of applications that run on multiple platforms.