C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Basic Syntax

In this tutorial, we'll cover the basic syntax of the C# programming language, including variables, data types, operators, control structures, loops, and methods.

  • Set up the environment

Create a new C# Console Application project in Visual Studio.

  • Variables and Data Types

C# has several built-in data types, such as int, float, double, bool, char, and string. To declare a variable, specify the data type followed by the variable name:

int age = 25;
float height = 5.9f;
double weight = 180.5;
bool isStudent = true;
char gender = 'M';
string name = "John Doe";
  • Operators

C# has arithmetic, comparison, and logical operators:

// Arithmetic operators: +, -, *, /, %
int sum = 10 + 20;
int difference = 30 - 10;
int product = 5 * 6;
int quotient = 50 / 10;
int remainder = 7 % 3;

// Comparison operators: ==, !=, <, >, <=, >=
bool isEqual = 5 == 5;
bool isNotEqual = 5 != 3;
bool isLess = 5 < 10;
bool isGreater = 10 > 5;
bool isLessOrEqual = 5 <= 5;
bool isGreaterOrEqual = 10 >= 5;

// Logical operators: &&, ||, !
bool result = (5 < 10) && (10 > 5); // true
bool anotherResult = (5 > 10) || (10 > 5); // true
bool notResult = !(5 > 10); // true
  • Control Structures

C# has control structures like if, else, and switch:

int grade = 85;

// if-else statement
if (grade >= 90)
{
    Console.WriteLine("A");
}
else if (grade >= 80)
{
    Console.WriteLine("B");
}
else if (grade >= 70)
{
    Console.WriteLine("C");
}
else
{
    Console.WriteLine("F");
}

// switch statement
switch (grade / 10)
{
    case 10:
    case 9:
        Console.WriteLine("A");
        break;
    case 8:
        Console.WriteLine("B");
        break;
    case 7:
        Console.WriteLine("C");
        break;
    default:
        Console.WriteLine("F");
        break;
}
  • Loops

C# has loops like for, foreach, while, and do-while:

// for loop
for (int i = 0; i < 5; i++)
{
    Console.WriteLine($"Iteration {i}");
}

// foreach loop
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine($"Number: {number}");
}

// while loop
int counter = 0;
while (counter < 5)
{
    Console.WriteLine($"Counter: {counter}");
    counter++;
}

// do-while loop
int anotherCounter = 0;
do
{
    Console.WriteLine($"Another Counter: {anotherCounter}");
    anotherCounter++;
} while (anotherCounter < 5);