I'm working with a C# class at the moment that exposes some lambda [instance] methods which serve as wrappers for static methods of the same name.

Here is an example snippet:

public class UserUI : DataUI
{
  // FYI: the `Context` object here is inherited from the `DataUI` base class
  public string GetUserId() => GetUserId(Context);

  public static string GetUserId(IDataUIContext context)
  {
    // ... logic here for pulling id from `context` ...
    return userId;
  }
}

I'm wondering: is there a name for such a design pattern as this?


Additionally, would it be possible to accomplish the same functionality using a class property here rather than an instance method / lambda?

Like so:

public class UserUI : DataUI
{
  public string GetUserId => GetUserId(Context);

  public static string GetUserId(IDataUIContext context)
  {
    // ... logic here for pulling id from `context` ...
    return userId;
  }
}

And, if so, is there any discernible difference between using a property / getter instead? (other than the method having to be invoked as opposed to being accessed like a field, obviously)

2

There are 2 best solutions below

0
T.S. On BEST ANSWER

Right now I can only think of a Proxy design pattern that can resemble what you have.

In the case when you need to present an object as an interface but your functionality implementation has only a static access, you can create a proxy such as

public static class Functionality  // may be in the different assembly
{
    public static string MethodA(IDataUIContext context)
    {
        // do something
    }
}

public interface IProxy
{
    string MethodA(IDataUIContext context);
}

public class Proxy : IProxy
{
    public string MethodA(IDataUIContext context) => Functionality.MethodA(context);
}

This is not a representation of the classic Go4 Proxy pattern but it is a variation

Continuation of this could be

public class Proxy2 : IProxy
{
    public string MethodA(IDataUIContext context) => AnotheFunctionality.ADifferentMethod(context);
}

0
Mark Seemann On

Is this a design pattern? Not a classic GoF one, but in general, this is just partial application, a well-know feature of many functional programming languages.

In genreal, you can think of any procedure with the type type public static string GetUserId(IDataUIContext context) as (if you drop the static keyword) an implementation of a single-method interface with this the method

public interface IMyInteface
{
    string GetUserId(IDataUIContext context)
}

which corresponds to a Func<IDataUIContext, string>. If you then define a lambda expression that closes over the input (IDataUIContext), you essentiall have yourself a string value. That's partial application in a nutshell.

Objects are just closures, so effectively the GetUserId method can be viewed as a function or object.