Vaccano
Vaccano

Reputation: 82291

Way to add an Extension method?

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"?

Upvotes: 2

Views: 410

Answers (6)

Steven Sudit
Steven Sudit

Reputation: 19620

Since what you want is impossible, why not fake it?

After all, it doesn't really matter if your parameterless GetLogger() method is on LogHelper. Just write your own static class, called MyLogHelper or something, and define the method there. The code would look like this:

public static class MyLogHelper
{
    public static ILog GetLogger()
    {
        return LogHelper.GetLogger("MyHardcodedValue");
    }
}

Upvotes: 2

Sergey Teplyakov
Sergey Teplyakov

Reputation: 11647

I see only one solution is to use optional arguments, but unfortunately they appear only in C# 4.0:

public static class LogHelper
{
    public static ILogger GetLogger(string name = "DefaultLoggerName")
    {
        ...
    }
}

Upvotes: 1

TrueWill
TrueWill

Reputation: 25523

I'm not sure how efficient this is, but it should work. log4net has an overload that accepts a Type, and you often want to name the logger after the fully qualified type name.

void Main()
{
    var foo = new Bar.Foo();
    ILog logger = foo.GetLogger();
}   

public static class LogHelper
{
    public static ILog GetLogger(this object o)
    {
        return LogManager.GetLogger(o.GetType());
    }
}

namespace Bar
{
    public class Foo {}
}

// Faking log4net
public class ILog {}
public class LogManager
{
    public static ILog GetLogger(Type type)
    {
        Console.WriteLine("Logger: " + type.ToString());
        return null;
    }
}

The above prints "Logger: Bar.Foo".

P.S. Use "this.GetLogger()" if you want a logger for the current class (assuming non-static method).

Upvotes: 3

Gage
Gage

Reputation: 7483

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.

Upvotes: 5

user438034
user438034

Reputation:

It is not possible to extend static classes with extension methods, unfortunately...

(I'm assuming your LogHelper is static? At least that's what I understood so far.)

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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();

Upvotes: 6

Related Questions