How to Use Reflection in C# to Dynamically Invoke Methods

Reflection in C# allows you to inspect and interact with types dynamically at runtime. It is useful for scenarios like plugin systems, dependency injection, and working with unknown assemblies.

Getting Started with Reflection

To use reflection, include the System.Reflection namespace:

using System;
using System.Reflection;

Invoking a Method Dynamically

You can use reflection to call methods on an object when you don't know the method name at compile time.

class Sample
{
    public void SayHello() => Console.WriteLine("Hello from Reflection!");
}

var sample = new Sample();
MethodInfo method = typeof(Sample).GetMethod("SayHello");
method?.Invoke(sample, null);
// Output: Hello from Reflection!

Invoking Methods with Parameters

If a method requires parameters, pass them as an object array:

class MathOperations
{
    public int Add(int a, int b) => a + b;
}

var math = new MathOperations();
MethodInfo method = typeof(MathOperations).GetMethod("Add");
object result = method?.Invoke(math, new object[] { 5, 3 });
Console.WriteLine(result); // Output: 8

Working with Static Methods

For static methods, pass null as the target object:

class Utility
{
    public static string GetMessage() => "Static method called!";
}

MethodInfo method = typeof(Utility).GetMethod("GetMessage");
object result = method?.Invoke(null, null);
Console.WriteLine(result); // Output: Static method called!

Performance Considerations

  • Reflection is slower than direct method calls because it bypasses compile-time optimizations.
  • Use Delegate.CreateDelegate to improve performance when invoking frequently:
Func<int, int, int> add = (Func<int, int, int>)Delegate.CreateDelegate(
    typeof(Func<int, int, int>),
    typeof(MathOperations).GetMethod("Add")
);
Console.WriteLine(add(5, 3)); // Output: 8

Conclusion

Reflection in C# is a powerful tool for dynamic method invocation. While it introduces some performance overhead, it is invaluable in scenarios requiring runtime flexibility, such as plugins, serialization, and dynamic dependency loading.

0
55

Related

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
226

Raw string literals in C# provide a flexible way to work with multiline strings, with some interesting rules around how quotes work.

The key insight is that you can use any number of double quotes (three or more) to delimit your string, as long as the opening and closing sequences have the same number of quotes.

The Basic Rules

  1. You must use at least three double quotes (""") to start and end a raw string literal
  2. The opening and closing quotes must have the same count
  3. The closing quotes must be on their own line for proper indentation
  4. If your string content contains a sequence of double quotes, you need to use more quotes in your delimiter than the longest sequence in your content

Examples with Different Quote Counts

// Three quotes - most common usage
string basic = """
    This is a basic
    multiline string
    """;

// Four quotes - when your content has three quotes
string withThreeQuotes = """"
    Here's some text with """quoted""" content
    """";

// Five quotes - when your content has four quotes
string withFourQuotes = """""
    Here's text with """"nested"""" quotes
    """"";

// Six quotes - for even more complex scenarios
string withFiveQuotes = """"""
    Look at these """""nested""""" quotes!
    """""";

The N+1 Rule

The general rule is that if your string content contains N consecutive double quotes, you need to wrap the entire string with at least N+1 quotes. This ensures the compiler can properly distinguish between your content and the string's delimiters.

// Example demonstrating the N+1 rule
string example1 = """
    No quotes inside
    """; // 3 quotes is fine

string example2 = """"
    Contains """three quotes"""
    """"; // Needs 4 quotes (3+1)

string example3 = """""
    Has """"four quotes""""
    """""; // Needs 5 quotes (4+1)

Practical Tips

  • Start with three quotes (""") as your default
  • Only increase the quote count when you actually need to embed quote sequences in your content
  • The closing quotes must be on their own line and should line up with the indentation you want
  • Any whitespace to the left of the closing quotes defines the baseline indentation
// Indentation example
string properlyIndented = """
    {
        "property": "value",
        "nested": {
            "deeper": "content"
        }
    }
    """; // This line's position determines the indentation

This flexibility with quote counts makes raw string literals extremely versatile, especially when dealing with content that itself contains quotes, like JSON, XML, or other structured text formats.

1
70

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
104