C# Cơ bản
Cú pháp cơ bản
Kiểu dữ liệu
C# có hai loại kiểu dữ liệu chính:
// Value types (lưu trên stack)
int number = 42;
double price = 19.99;
bool isActive = true;
char letter = 'A';
DateTime now = DateTime.Now;
// Reference types (lưu trên heap)
string name = "John";
object obj = new object();
int[] numbers = new int[] { 1, 2, 3 };
Biến và Hằng số
// Biến thông thường
var message = "Hello"; // Type inference
string name = "Alice";
// Hằng số
const int MaxUsers = 100;
const string AppName = "MyApp";
// Readonly (chỉ gán trong constructor)
readonly string _connectionString;
Toán tử
// Toán tử số học
int sum = 5 + 3; // 8
int diff = 10 - 4; // 6
int product = 6 * 7; // 42
int quotient = 15 / 3; // 5
int remainder = 10 % 3; // 1
// Toán tử so sánh
bool isEqual = (5 == 5); // true
bool notEqual = (5 != 3); // true
bool greaterThan = (10 > 5); // true
bool lessThan = (3 < 7); // true
// Toán tử logic
bool and = (true && false); // false
bool or = (true || false); // true
bool not = !true; // false
// Toán tử ternary
int score = 85;
string grade = score >= 60 ? "Pass" : "Fail"; // "Pass"
Luồng điều khiển
// if-else
if (age >= 18)
{
Console.WriteLine("Adult");
}
else if (age >= 13)
{
Console.WriteLine("Teenager");
}
else
{
Console.WriteLine("Child");
}
// switch
string day = "Monday";
switch (day)
{
case "Monday":
Console.WriteLine("Start of week");
break;
case "Friday":
Console.WriteLine("Weekend is near");
break;
default:
Console.WriteLine("Midweek");
break;
}
// Vòng lặp
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
int count = 0;
while (count < 5)
{
Console.WriteLine(count);
count++;
}
do
{
Console.WriteLine("At least once");
} while (false);
// foreach
string[] names = { "Alice", "Bob", "Charlie" };
foreach (string name in names)
{
Console.WriteLine(name);
}
Phương thức
// Method với parameters và return type
public int Add(int a, int b)
{
return a + b;
}
// Optional parameters
public void Greet(string name = "Guest")
{
Console.WriteLine($"Hello, {name}!");
}
// Method overloading
public int Multiply(int a, int b) => a * b;
public double Multiply(double a, double b) => a * b;
// ref, out, in parameters
public void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
public bool TryParse(string input, out int result)
{
return int.TryParse(input, out result);
}
public double Calculate(in double value)
{
// value cannot be modified
return value * 2;
}