C# Basic syntax
here's an overview of the basic syntax of C#:
Comments
Comments are used to explain the code and improve its readability. In C#, single-line comments start with //
, while multi-line comments are enclosed in /*
and */
. For example:
// This is a single-line comment /* This is a multi-line comment */
Variables and Data Types
In C#, variables are used to store values of different types, such as integers, floating-point numbers, strings, and more. Here's an example of declaring and initializing some variables:
int age = 30; float height = 1.75f; string name = "John"; bool isMarried = false;
The int
type represents integers, float
represents floating-point numbers, string
represents text, and bool
represents boolean values (true
or false
).
Operators
C# has a variety of operators that can be used to perform arithmetic operations, comparison operations, logical operations, and more. Here are some examples:
int x = 10; int y = 20; int sum = x + y; // Addition int diff = y - x; // Subtraction int product = x * y; // Multiplication float quotient = y / x; // Division bool isEqual = x == y; // Comparison (equal to) bool isGreater = y > x; // Comparison (greater than) bool isLessOrEqual = x <= y; // Comparison (less than or equal to) bool isNotEqual = x != y; // Comparison (not equal to) bool isTrue = true && false; // Logical AND bool isFalse = true || false; // Logical OR bool isNot = !true; // Logical NOT
Conditional Statements
Conditional statements are used to execute code based on a certain condition. In C#, the if
statement is used for this purpose. Here's an example:
int age = 30; if (age >= 18) { Console.WriteLine("You are an adult."); } else { Console.WriteLine("You are not yet an adult."); }
In this example, we use the if
statement to check whether the age
variable is greater than or equal to 18
. If it is, we print the message "You are an adult." If not, we print the message "You are not yet an adult."
Loops
Loops are used to execute code repeatedly. In C#, the while
and for
loops are commonly used for this purpose. Here's an example of a while
loop:
int i = 0; while (i < 10) { Console.WriteLine(i); i++; }
In this example, we use a while
loop to print the numbers from 0
to 9
to the console.
Here's an example of a for
loop:
for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
In this example, we use a for
loop to achieve the same result as the previous example. The for
loop has three parts: an initialization statement (int i = 0
), a condition (i < 10
), and an iteration statement (i++
).