C# (pronounced "C Sharp") is a modern, object-oriented programming language developed by Microsoft as part of the .NET framework. It's widely used for developing desktop applications, web services, and games using Unity. This tutorial will guide you through setting up your environment, understanding basic syntax, and writing your first C# program.
Before diving into coding, ensure you have the necessary tools installed:
The .NET SDK is included in Visual Studio installations. However, if you prefer a standalone version:
Let's start by writing a simple "Hello, World!" program in C#. This will help you understand basic syntax and structure.
HelloWorld) and choose a location to save it.Visual Studio will generate some boilerplate code for you. Replace it with the following:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
using System;: This directive includes the System namespace, which contains fundamental classes like Console.namespace HelloWorld: Defines a namespace for your program. It helps organize code and avoid naming conflicts.class Program: A class is a blueprint for creating objects. In C#, every application must have at least one class.static void Main(string[] args): The entry point of the application. Main is where execution begins.F5 or click on "Start" in Visual Studio to run your program.C# is a statically typed language, meaning you must declare the type of each variable before using it.
int number = 10; // Integer
double price = 19.99; // Double-precision floating-point
string name = "Alice"; // String
bool isActive = true; // Boolean
Comments are used to explain code and are ignored by the compiler.
// Single-line comment
/*
Multi-line comment
*/
C# supports various operators for arithmetic, comparison, logical operations, etc.
int a = 5;
int b = 3;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
double quotient = (double)a / b; // Division with type casting
bool isEqual = a == b; // Equality check
Control flow is essential for making decisions in your code.
if (a > b)
{
Console.WriteLine("a is greater than b");
}
else if (a < b)
{
Console.WriteLine("b is greater than a");
}
else
{
Console.WriteLine("a and b are equal");
}
Loops allow you to execute code repeatedly.
// For loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// While loop
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
This tutorial has covered the basics of getting started with C#. You've learned how to set up your environment, write a simple program, understand basic syntax, and use control structures. As you progress, you'll explore more advanced features like object-oriented programming, LINQ, and asynchronous programming. Happy coding!