C# Language Fundamentals
This section provides a deep dive into the core language constructs of C#, enabling you to build robust and efficient .NET applications.
Variables and Data Types
Understanding data types is fundamental to programming. C# offers a rich set of built-in value types and reference types.
Value Types
Value types directly contain their data. Examples include:
int: 32-bit signed integer.float: Single-precision 32-bit floating-point number.double: Double-precision 64-bit floating-point number.bool: Boolean value (trueorfalse).char: 16-bit Unicode character.struct: User-defined composite types.
Reference Types
Reference types store a reference to the object's location in memory. Examples include:
class: User-defined composite types.string: Immutable sequence of Unicode characters.array: A fixed-size sequence of elements of the same type.interface: A contract that defines a set of members.
int age = 30;
string name = "Alice";
bool isActive = true;
double price = 99.99;
Operators
Operators perform operations on operands. C# supports various categories of operators:
- Arithmetic operators:
+,-,*,/,% - Comparison operators:
==,!=,<,>,<=,>= - Logical operators:
&&,||,! - Assignment operators:
=,+=,-=,*=,/= - Increment/Decrement operators:
++,--
int x = 10;
int y = 5;
int sum = x + y; // sum is 15
bool isGreater = x > y; // isGreater is true
Control Flow Statements
Control flow statements dictate the order in which code is executed.
Conditional Statements
if,else if,else: Execute blocks of code based on conditions.switch: Select one of many code blocks to be executed.
if (temperature > 30) {
Console.WriteLine("It's hot!");
} else if (temperature < 10) {
Console.WriteLine("It's cold!");
} else {
Console.WriteLine("It's moderate.");
}
Looping Statements
for: Repeats a statement or group of statements when a control expression evaluates to true.while: Executes a statement or group of statements while a Boolean expression evaluates to true.do-while: Executes a statement or group of statements at least once, and then repeats the execution while a Boolean expression evaluates to true.foreach: Iterates through a collection.
for (int i = 0; i < 5; i++) {
Console.WriteLine($"Iteration: {i}");
}
string[] fruits = {"Apple", "Banana", "Cherry"};
foreach (string fruit in fruits) {
Console.WriteLine(fruit);
}
Methods
Methods are blocks of code that perform a specific task. They help in modularizing code and promoting reusability.
public int Add(int a, int b) {
return a + b;
}
int result = Add(5, 3); // result is 8
Key Takeaway
Mastering these fundamental building blocks is crucial for any C# developer. They form the basis of more complex programming patterns and application development.