Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Share properties, events, and methods across unrelated classes

Tags:

c#

oop

events

I need to add the following to several unrelated classes:

private MyClass myclass;

private EventHandler clicked;
public event EventHandler Clicked { ... }

private bool enabled;
public bool Enabled { ... }

private void HandleClicked(object sender, EventArgs e) { ... }

The problem is these classes are third-party and do not necessarily share the same immediate base class though they all eventually inherit from a class called View. Right now, I end up creating my own subclasses for each and copy-pasting the same code which leads to unnecessary duplication.

Any way to meaningfully refactor this?

like image 202
Mark13426 Avatar asked Jan 19 '26 11:01

Mark13426


1 Answers

One of the way is to use composition. Create class which will store all new events\properties\methods:

public class Properties
{
  private MyClass myclass;

  private EventHandler clicked;
  public event EventHandler Clicked { ... }

  private bool enabled;
  public bool Enabled { ... }

  private void HandleClicked(object sender, EventArgs e) { ... }
}

Then use Extension methods to expand required interface (i.e. classA)

public static class NewInterfaces
{
   public static Properties Props(this classA)
   {  /* lookup required properties, from some associative storage */ }
}

Usage will look like:

var inst = new classA();
inst.Prop.Enabled = !inst.Prop.Enabled;

Second way it still composition, but you will use wrapper for those:

public class Wrapper
{
  private object _wrapped;

  public Wrapper(classA obj)
  {
    _wrapped = obj;
  }

  public Wrapper(classB obj)
  {
    _wrapped = obj;
  }

  public int WrappedProperty
  { 
    get
    {
      var instA = _wrapped as classA;
      if (instA != null)
        return instA.SomeProperty1;
      var instB = _wrapped as classB;
      if (instB != null)
        return instB.SomeProperty2;
    }
  }

  private MyClass myclass;

  private EventHandler clicked;
  public event EventHandler Clicked { ... }

  private bool enabled;
  public bool Enabled { ... }

  private void HandleClicked(object sender, EventArgs e) { ... }
}

Second way allow you to create new hierarchy of wrapper which will contain elements without common base class.

like image 55
lerthe61 Avatar answered Jan 21 '26 02:01

lerthe61



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!