In C#, string interpolation ($"...") is more readable and safer than using String.Format.
int a = 18, b = 22;
string text;
// Old approach
text = string.Format("number1: {0}, number2: {1}", a, b);
// Recommended approach
text = $"number1: {a}, number2: {b}";
In C#, avoid catching the general Exception. Catch only the exceptions you expect to handle to prevent hiding real problems.
// Risky usage: hides the real problem
try
{
int number = int.Parse(input);
}
catch (Exception)
{
Console.WriteLine("Something went wrong");
}
// Recommended usage: catch specific exception
try
{
int number = int.Parse(input);
}
catch (FormatException)
{
Console.WriteLine("Input is not a valid number");
}
In C#, modifying a collection inside a foreach loop causes runtime errors. If you need to change the collection, iterate over a copy or use a different loop.
// This will cause an error
foreach (var item in items)
{
items.Remove(item);
}
// Safe approach: iterate over a copy
foreach (var item in items.ToList())
{
items.Remove(item);
}
// Alternative: use for loop
for (int i = items.Count - 1; i >= 0; i--)
{
items.RemoveAt(i);
}
In C#, const values are fixed at compile time, while readonly values can be assigned at runtime, usually in the constructor.
// const: value must be known at compile time
public const int MaxItems = 10;
// readonly: value can be set at runtime
public readonly int Timeout;
public Settings()
{
Timeout = GetTimeoutFromConfig();
}
In C#, you can use using var to manage disposable resources in a shorter and more readable way when the scope is clear.
// Classic using block
using (var stream = new FileStream(path, FileMode.Open))
{
// use stream
}
// using var (recommended for short scopes)
using var stream2 = new FileStream(path, FileMode.Open);
// use stream2
When comparing strings in C#, using StringComparison helps prevent culture- and case-related bugs.
string a = "london";
string b = "LONDON";
bool eq1 = a == b;
bool eq2 = string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
Console.WriteLine(eq1); // False
Console.WriteLine(eq2); // True
In C#, use a for loop instead of foreach when you need the index or when you need to modify the collection safely.
// foreach: index bilgisi yok
foreach (var item in items)
{
Console.WriteLine(item);
}
// for: index gerektiğinde
for (int i = 0; i < items.Count; i++)
{
Console.WriteLine($"{i}: {items[i]}");
}
// for: eleman silme gibi durumlarda daha güvenli
for (int i = items.Count - 1; i >= 0; i--)
{
items.RemoveAt(i);
}
In C#, use is and is not for more readable type checks and pattern matching.
// Old approach (using "as" and null check)
object obj = "Hello, world!";
if (obj is string)
{
Console.WriteLine(((string)obj).ToUpper()); // HELLO, WORLD!
}
// Recommended approach (using is)
if (obj is string str)
{
Console.WriteLine(str.ToUpper()); // HELLO, WORLD!
}
// Using "is not" for negation
if (obj is not int)
{
Console.WriteLine("Not an integer");
}
In C#, var should be used when the type is clearly understood from the right side. It improves readability without hiding information.
// Clear and readable: type is obvious
var numbers = new List<int>();
var name = "Alice";
var total = numbers.Count;
// Not recommended: type is not obvious
var result = GetData();
// Recommended alternative
List<User> users = GetUsers();
In C#, use string.IsNullOrWhiteSpace() to check text values instead of checking only for null or empty strings.
// Risky checks
if (text == null || text == "")
{
Console.WriteLine("Invalid text");
}
// Safe and recommended check
if (string.IsNullOrWhiteSpace(text))
{
Console.WriteLine("Invalid text");
}