Learn C#: Refactor Code

How to Refactor Code in C#

Refactoring is the process of improving code readability, maintainability, and efficiency without changing its behavior.

1. Remove Redundant Code

Before

List<int> userIds = new List<int>();
userIds.AddRange(output.Select(s => s.UserId).Distinct().ToList());
userIds = userIds.Distinct().ToList();

After

var userIds = output.Select(s => s.UserId).Distinct().ToList();

2. Use LINQ Instead of Loops

Before

List<int> evenNumbers = new List<int>();
foreach (var num in numbers) {
    if (num % 2 == 0) {
        evenNumbers.Add(num);
    }
}

After

var evenNumbers = numbers.Where(n => n % 2 == 0).ToList();

3. Avoid Repeating Code (Use Methods)

Before

var segmentIDs = output.Select(s => s.SegmentID).Distinct().ToList();
if (segmentIDs.Any()) {
    segments = db.CheckCode
        .Where(c => segmentIDs.Contains(c.CheckCodeID))
        .ToList();
}

After

List<int> GetDistinctIDs(IEnumerable<T> source, Func<T, int?> selector) =>
    source.Select(selector).Where(id => id.HasValue).Select(id => id.Value).Distinct().ToList();

4. Use Null-Coalescing and Ternary Operators

Before

string name;
if (user != null && user.Name != null) {
    name = user.Name;
} else {
    name = "Unknown";
}

After

string name = user?.Name ?? "Unknown";

5. Use var for Readability

Before

List<int> numbers = new List<int> { 1, 2, 3, 4 };

After

var numbers = new List<int> { 1, 2, 3, 4 };

6. Avoid Nested if Statements

Before

if (user != null) {
    if (user.Age > 18) {
        Console.WriteLine("Adult");
    }
}

After

if (user == null) return;
if (user.Age <= 18) return;
Console.WriteLine("Adult");

7. Use String Interpolation

Before

string message = string.Format("Hello, {0}! You have {1} messages.", name, count);

After

string message = $"Hello, {name}! You have {count} messages.";

8. Use async/await for Performance

Before

public List<User> GetUsers() {
    return db.Users.ToList();
}

After

public async Task<List<User>> GetUsersAsync() {
    return await db.Users.ToListAsync();
}

Final Thoughts

Always aim for

  • Readability: Code should be easy to understand.
  • Maintainability: Future developers should easily modify the code.
  • Performance: Avoid unnecessary computations.
  • DRY (Don’t Repeat Yourself): Extract reusable logic into methods.

Up Next
    Ebook Download
    View all
    DateTime in C#
    Read by 1.3k people
    Download Now!
    Learn
    View all