Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to add an Extension method?

Tags:

c#

c#-3.0

Say I have a class called LogHelper and it has a static method called GetLogger(string name).

Is there a way to add a static extension method that would just be GetLogger()?

I know that normally extension methods are static where they are declared, but is there a way to appear static on the class they are "Helping"?

like image 792
Vaccano Avatar asked Dec 01 '25 08:12

Vaccano


2 Answers

You could use an extension method:

public static class StringExtensions
{
    public static ILogger GetLogger(this string value)
    {
        ...
    }
}

And then you could use like this:

string foo = "bar";
ILogger logger = foo.GetLogger();
like image 133
Darin Dimitrov Avatar answered Dec 03 '25 23:12

Darin Dimitrov


You can also use

    public static ILogger GetLogger(string value)
    {
        ...
    }

    public static ILogger GetLogger()
    {
        return GetLogger("Default Value");
    }

This way when you called GetLogger() it would call GetLogger(string value) but with your default value.

like image 29
Gage Avatar answered Dec 04 '25 00:12

Gage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!