- C# Tip: Null Coalescing Operator (??)
Assign a default value if null:
string name = null; string displayName = name ?? "Guest"; Console.WriteLine(displayName); // Output: Guest
Shorter & cleaner than if checks!
2. C# Tip: using for Automatic Resource Cleanup
Dispose objects automatically:
using (var reader = new StreamReader("file.txt"))
{
Console.WriteLine(reader.ReadToEnd());
} // Auto-disposes here
No need for manual Dispose()!
3. C# Tip: String Formatting with string.Join
Quickly join array elements into a string:
var items = new[] { "Apple", "Banana", "Cherry" };
string result = string.Join(", ", items);
Console.WriteLine(result); // Apple, Banana, Cherry
Clean & efficient!
4. C# Tip: Use ?. for Null Safety
Avoid NullReferenceException with safe navigation:
string name = person?.FullName; // Returns null if person is null
No need for extra null checks!
5. C# Tip: Use switch Expression for Simplicity
Instead of:
string GetStatus(int code)
{
switch (code)
{
case 1: return "Active";
case 2: return "Inactive";
default: return "Unknown";
}
}
Use switch expression:
string GetStatus(int code) => code switch {
1 => "Active",
2 => "Inactive",
_ => "Unknown"
};
More concise & readable!
6. C# Tip: Use TryParse to Avoid Exceptions
Instead of:
int number = int.Parse(input); // Throws exception if input is invalid
Use TryParse for safe conversion:
if (int.TryParse(input, out int number))
{
Console.WriteLine($"Valid number: {number}");
}
else
{
Console.WriteLine("Invalid input!");
}
No exceptions, better performance!
7. C# Tip: Use ??= to Assign Default Values
Instead of:
if (name == null)
name = "Guest";
Use null-coalescing assignment:
name ??= "Guest";
Shorter, cleaner, and more efficient!
8. C# Tip: Use string.IsNullOrWhiteSpace
Instead of:
if (str == null || str.Trim() == "")
Use IsNullOrWhiteSpace for better readability:
if (string.IsNullOrWhiteSpace(str))
Cleaner & more efficient!
#CSharp #DotNet #BestPractices #CodingTips #DevLife
bala kumarPosted Mar 28, 2019, 1:41 PM
Hi, good article. Nice tips. Can u explain last one how it display "I am a B"
SubashPosted Jul 29, 2016, 4:33 AM
Thanks For Your Tips
Tarique EhsanPosted Sep 20, 2015, 10:38 AM
nice
Michal HabalcikPosted Dec 3, 2014, 1:04 AM
some good tricks out there, thanks
Sanjay GuptaPosted Dec 3, 2014, 12:06 AM
Nice information. Some are really useful. Thanks for sharing!
Dev EstacionPosted Dec 2, 2014, 9:28 PM
Nice article, thanks.