C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft. It's part of the .NET framework and offers a powerful, type-safe approach to software development.
To begin programming in C#, you'll need to set up your development environment. This typically involves installing Visual Studio or Visual Studio Code with the .NET SDK.
C# syntax is similar to other C-style languages. Here's a simple "Hello, World!" program:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}
Let's break down this example:
using System;
imports the System namespace.class Program
defines the main class of our program.static void Main()
is the entry point of the application.Console.WriteLine()
outputs text to the console.C# is a strongly-typed language, meaning you must declare a variable's type before using it. Common data types include:
int
for integersdouble
for floating-point numbersstring
for textbool
for boolean valuesHere's an example of declaring and using variables:
int age = 25;
string name = "John";
bool isStudent = true;
Console.WriteLine($"Name: {name}, Age: {age}, Is Student: {isStudent}");
C# supports various control structures for decision-making and looping:
Use if-else statements for conditional execution:
if (age >= 18)
{
Console.WriteLine("You are an adult.");
}
else
{
Console.WriteLine("You are a minor.");
}
C# offers several types of loops, including for loops, while loops, and foreach loops:
// For loop
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// While loop
int j = 0;
while (j < 5)
{
Console.WriteLine(j);
j++;
}
// Foreach loop
string[] fruits = { "apple", "banana", "orange" };
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
C# is an object-oriented language, supporting concepts like classes and objects, inheritance, and polymorphism. Here's a simple class example:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public void Introduce()
{
Console.WriteLine($"Hi, I'm {Name} and I'm {Age} years old.");
}
}
// Usage
Person person = new Person { Name = "Alice", Age = 30 };
person.Introduce();
As you continue your C# journey, explore these important topics:
With this introduction, you're ready to start your C# programming journey. Practice regularly, explore the documentation, and don't hesitate to experiment with different concepts to deepen your understanding.