Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Multiple Inheritance with Non-Abstract Computed Properties

I'm creating a series of Interfaces/Abstract classes that contain basic properties and I would like to have computed Properties and multiple inheritance.

public abstract class /interface Modifiable
{
   public DateTime ModifiedDate {get; set;}

   public boo ModifiedToday
   {
     get { return DateTime.Now.AddDays(-1).CompareTo(ModifiedDate) >= 0; }
   } 

   public bool ModifiedInLastWeek
   {
     get { return DateTime.Now.AddDays(-7).CompareTo(ModifiedDate) >= 0; }
   }
}

public abstract class /interface Deletable
{
   public DateTime DeletionDate {get; set;}    

   public bool Deleted
   {
     get { return DeletionDate != default(DateTime) }
   }
}

Then I have a class that inherits from these two Interfaces/Abstract classes.

public class Something : Modifiable, Deletable 
{
  //
}

But a class cannot inherit from two abstract classes. So I then need to use interfaces, but with interfaces I cannot have method bodies. I then have to define the same exact functions across multiple classes to implement these simple bool properties using interfaces.

I also don't want to have Modifiable inherit from Deletable because I might want something to be Modifiable but not Deletable. These specific classes aren't my problem, I'm simply using them to illustrate my problem.

Is there a design pattern that mimics an abstract class by allowing function bodies, but allows multiple inheritors like an interface?

like image 248
Mike Avatar asked Oct 11 '22 14:10

Mike


1 Answers

It's not multiple inheritance, but something that comes to mind is Extension methods.

public interface IModifiable
{
    DateTime ModifiedDate {get; set;}
}

public static class ModifiableExtensions
{
   public bool ModifiedToday(this IModifiable m)
   {
      return DateTime.Now.AddDays(-1).CompareTo(m.ModifiedDate) >= 0;
   } 

   public bool ModifiedInLastWeek(this IModifiable m)
   {
     return DateTime.Now.AddDays(-7).CompareTo(m.ModifiedDate) >= 0; 
   }

}

That gives the "feel" of helper methods that are baked into the type, but they happen to be declared elsewhere. Take this class:

public class MyModifiable :IModifiable
{
     public ModifiedDate {get; set;}
}

And you can do this:

MyModifiable m = new MyModifiable;

m.ModifiedDate = DateTime.Now;

bool isToday = m.ModifiedToday();
like image 111
RQDQ Avatar answered Oct 21 '22 17:10

RQDQ