Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast Way To Forward Property Implementation to Property of a member

Tags:

c#

properties

I spent another day writing boiler code and I need to find a quicker way. Not all Interface implementations are trivial but there is one case that seems to be super trivial for me.

Suppose I have a property with a getter and a setter that need to be forwarded to a members property that also has a getter and a setter. What is the fastest way of writing that?

Here is a compiling example that is close to being minimal. See in the comment what I would like to write.

//Core is unchangeable external code
class Core
{
    public int prop { get; set; }
    public Core() { prop = 42; }
}

//Boilerfun can be modified
interface IBoilderFun
{
    int Prop { get; set; }
}

//This implements the adapter for the boiler special case Core
class CoreBoilerAdapter : IBoilderFun
{
    private Core core;

    public CoreBoilerAdapter(Core core)
    {
        this.core = core;
    }

    public int Prop
    {
        get { return core.prop; }
        set { core.prop = value; }
    }
    //public int Prop { core.prop; } <-- this would be awsome
}

class Program
{
    static void Main(string[] args)
    {
        IBoilderFun bf = InstanciateBasedOnConfig();
        System.Console.WriteLine(bf.Prop);
    }

    private static IBoilderFun InstanciateBasedOnConfig()
    {
        return new CoreBoilerAdapter(new Core());
    }
}
like image 206
Johannes Avatar asked Sep 14 '25 22:09

Johannes


1 Answers

Resharper has a feature called "Generate delegating members". Otherwise, you could spend a few hours writing a Roslyn-based refactoring.

like image 96
usr Avatar answered Sep 16 '25 11:09

usr