How to Use the nameof Operator for Safer Refactoring in C#

Refactoring code can be risky, especially when dealing with hardcoded string literals representing variable, property, or method names.

One small change in a name could lead to runtime errors that are difficult to track down. Fortunately, C# provides the nameof operator to make refactoring safer and more maintainable.

What is the nameof Operator?

The nameof operator in C# returns the string representation of a variable, method, or class name at compile time. This makes your code more resilient to name changes since the compiler will catch errors if a referenced identifier is renamed or removed.

Basic Usage

Instead of using hardcoded strings, use nameof to reference identifiers dynamically:

class Person
{
    public string FirstName { get; set; }
}

void PrintPropertyName()
{
    Console.WriteLine(nameof(Person.FirstName)); // Output: "FirstName"
}

If FirstName is renamed, the compiler will flag the change, helping prevent runtime errors.

Benefits of Using nameof

  1. Safer Refactoring: When renaming identifiers, the compiler ensures nameof references update automatically.
  2. Improved Readability: Code intent is clearer, avoiding magic strings.
  3. Fewer Runtime Errors: No risk of typos or mismatches in string literals.

Practical Examples

Logging

Using nameof ensures that logs remain accurate even after refactoring:

void LogError(string message, string propertyName)
{
    Console.WriteLine($"Error in {propertyName}: {message}");
}

LogError("Invalid value", nameof(Person.FirstName));

Argument Validation

Validating method parameters without hardcoded strings:

void SetAge(int age)
{
    if (age < 0)
        throw new ArgumentException("Age cannot be negative", nameof(age));
}

Dependency Injection

When working with DI frameworks, nameof prevents issues with binding:

services.AddSingleton<ILogger, Logger>(provider =>
    new Logger(nameof(Logger)));

Conclusion

The nameof operator is a simple yet powerful feature in C# that improves code maintainability and prevents common errors during refactoring. By replacing hardcoded strings with nameof, you can make your applications more robust and future-proof.

0
19

Related

When working with SQL Server, you may often need to count the number of unique values in a specific column. This is useful for analyzing data, detecting duplicates, and understanding dataset distributions.

Using COUNT(DISTINCT column_name)

To count the number of unique values in a column, SQL Server provides the COUNT(DISTINCT column_name) function. Here’s a simple example:

SELECT COUNT(DISTINCT column_name) AS distinct_count
FROM table_name;

This query will return the number of unique values in column_name.

Counting Distinct Values Across Multiple Columns

If you need to count distinct combinations of multiple columns, you can use a subquery:

SELECT COUNT(*) AS distinct_count
FROM (SELECT DISTINCT column1, column2 FROM table_name) AS subquery;

This approach ensures that only unique pairs of column1 and column2 are counted.

Why Use COUNT DISTINCT?

  • Helps in identifying unique entries in a dataset.
  • Useful for reporting and analytics.
  • Efficient way to check for duplicates.

By leveraging COUNT(DISTINCT column_name), you can efficiently analyze your database and extract meaningful insights. Happy querying!

0
106

Reading a file line by line is useful when handling large files without loading everything into memory at once.

✅ Best Practice: Use File.ReadLines() which is more memory efficient.

Example

foreach (string line in File.ReadLines("file.txt"))
{
    Console.WriteLine(line);
}

Why use ReadLines()?

Reads one line at a time, reducing overall memory usage. Ideal for large files (e.g., logs, CSVs).

Alternative: Use StreamReader (More Control)

For scenarios where you need custom processing while reading the contents of the file:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string? line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

Why use StreamReader?

Lets you handle exceptions, encoding, and buffering. Supports custom processing (e.g., search for a keyword while reading).

When to Use ReadAllLines()? If you need all lines at once, use:

string[] lines = File.ReadAllLines("file.txt");

Caution: Loads the entire file into memory—avoid for large files!

3
264

Storing passwords as plain text is dangerous. Instead, you should hash them using a strong, slow hashing algorithm like BCrypt, which includes built-in salting and resistance to brute-force attacks.

Step 1: Install BCrypt NuGet Package

Before using BCrypt, install the BCrypt.Net-Next package:

dotnet add package BCrypt.Net-Next

or via NuGet Package Manager:

Install-Package BCrypt.Net-Next

Step 2: Hash a Password

Use BCrypt.HashPassword() to securely hash a password before storing it:

using BCrypt.Net;

string password = "mySecurePassword123";
string hashedPassword = BCrypt.HashPassword(password);

Console.WriteLine(hashedPassword); // Output: $2a$12$...

Step 3: Verify a Password

To check a user's login attempt, use BCrypt.Verify():

bool isMatch = BCrypt.Verify("mySecurePassword123", hashedPassword);
Console.WriteLine(isMatch); // Output: True

Ensuring proper hashing should be at the top of your list when it comes to building authentication systems.

2
233