C# Basic

C# syntax and code structure

Let’s embark on an exciting journey into the world of C#! The syntax of C# is straightforward, making it a breeze to understand and write code. Embrace the use of curly braces to define code blocks. For instance:

using System;

class Program
static void Main()
Console.WriteLine(“Hello, C#!”);

Variables, data types, and type casting

In C#, variables are indispensable containers that hold data. But remember, before using a variable, it’s crucial to declare its data type. C# has an array of data types like int, double, string, and bool. And here comes the magic of type casting, allowing us to convert data from one type to another:

int age = 30;
double height = 5.9;
string name = “John”;
bool isStudent = true;

// Type casting example
int result = (int)(height + age);

Operators and expressions

Behold the mighty operators, the symbols that work wonders on variables or values! In C#, you get a variety of operators: arithmetic, comparison, logical, and assignment operators:

int num1 = 10;
int num2 = 5;

int sum = num1 + num2;
bool isEqual = (num1 == num2);
bool isGreater = (num1 > num2);

Control flow (if-else, switch)

With the power of control flow, we can make decisions based on specific conditions. The if-else statement comes to the rescue for decision-making, while the switch statement simplifies handling multiple conditions:

int grade = 80;

if (grade >= 90)
else if (grade >= 70)
Console.WriteLine(“Good job!”);
Console.WriteLine(“Keep working hard.”);

// Switch statement example
string day = “Monday”;

switch (day)
case “Monday”:
Console.WriteLine(“It’s the start of the week.”);
case “Friday”:
Console.WriteLine(“It’s finally Friday!”);
Console.WriteLine(“Enjoy your day!”);

Loops (for, while, do-while)

Loops are the guardians of repetition in C#. Behold three mighty loops: for, while, and do-while, each with its unique powers:

// For loop example
for (int i = 1; i <= 5; i++)
Console.WriteLine(“Count: ” + i);

// While loop example
int counter = 0;
while (counter < 5)
Console.WriteLine(“Counter: ” + counter);

// Do-while loop example
int number = 10;
} while (number > 0);

Exception handling

Even in the realm of programming, handling exceptions gracefully is vital. It empowers us to deal with unexpected errors in our code:

int numerator = 10;
int denominator = 0;
int result = numerator / denominator;
catch (DivideByZeroException ex)
Console.WriteLine(“Error: ” + ex.Message);
Console.WriteLine(“End of exception handling.”);


In conclusion, C# basics form the foundation to unlock the true power of programming. Understanding its syntax, variables, data types, operators, control flow, loops, and exception handling is paramount for building robust and efficient applications. So, dive into C#, experiment with the examples, and embrace the world of coding possibilities that this versatile language offers!

Leave a Comment