C#: Multiple Inheritance with Non-Abstract Computed Properties - c#

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?

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

No. C# doesn't have a mechanism to implement multiple inheritance this way.
When it comes to interfaces, this is possible because when you define multiple interfaces you also need to implement them all.
Consider a different design, possibly using composition in order to reuse the classes you want to use for multiple inheritance.

I forget the design pattern name, but there's a pattern to implement multiple interfaces by wrapping the method/property calls around interface implementations of members who are of that same interface:
interface IDrivable {
void Drive();
}
interface IFlyable {
void Fly();
}
class Car : IDrivable {
public void Drive() { /* Implementation */ }
}
class Plane : IFlyable {
public void Fly() { /* Implementation */ }
}
class MyClass : IDrivable, IFlyable {
private IDrivable _car = new Car();
private IFlyable _plane = new Plane();
public void Drive() { _car.Drive(); }
public void Fly() { _plane.Fly(); }
}

Yes there are methods, several, actually. A few thoughts:
Use an empty interface for Deletable, Modifiable etc (called marker interfaces), then create extension methods for them. This is not as expandable as multiple inheritance, but it gets a long way.
Use genericity, possibly with the same tagging interfaces to create dependencies. This way you can have a base class with all methods for both Modifiable and Deletable, including abstract methods and override implementation in derived classes
Use aspect oriented programming to get to the same results
Almost the same, but do it yourself with Castle or similar library, possibly with the help of attributes.
Obviously, none of the above has all the advantages of multiple inheritance. If you want multiple inheritance in .NET, you can use C++.NET or Eiffel.NET.

Sorry, multiple inheritance is not possible in C# and that's a bummer for you. Your choices are:
Either to chain your base class inheritance a la MyClass : MyBaseClass : EvenBasierClass
Or inherit from multiple interfaces. And implement all methods of all interfaces.
It's not pretty, but you can also control property accessibility or return values inside your classes by checking the instance type.

Modifiable & Deletable IMO should be interfaces, not base classes. A base class defines what a type is, whereas a interface describes what a type does.
As far as implementing the code, you can always use extension methods:
public interface IModifiable
{
public DateTime ModifiedDate {get; set;}
}
public interface IDeletable
{
public DateTime DeletionDate {get; set;}
}
public static class SomeExtentions
{
public static bool IsModifiedToday(this IModifiable modifiable)
{
return DateTime.Now.AddDays(-1).CompareTo(modifiable.ModifiedDate) >= 0;
}
public static bool IsModifiedInLastWeek(this IModifiable modifiable)
{
return DateTime.Now.AddDays(-7).CompareTo(modifiable.ModifiedDate) >= 0;
}
public static bool IsDeleted(this IDeletable deletable)
{
return deletable.DeletionDate != default(DateTime);
}
}

I would probably use delegation to achieve this. Create Modifiable and Deletable as interfaces, then create implementations of those. Give the Something class instances of these implementations. Here's an example for Deletable:
public interface Deletable
{
DateTime DeletionDate{get;set;}
bool Deleted{get;}
}
public class DeletableImpl : Deletable
{
public DateTime DeletionDate{get; set;}
public bool Deleted{get {return DeletionDate != default(DateTime);}}
}
// Do the same thing with Modifiable and ModifiableImpl
public class Something : Deletable, Modifiable
{
private Deletable _deletable = new DeletableImpl();
private Modifiable _modifiable = new ModifiableImpl();
public DateTime DeletionDate
{
get{return _deletable.DeletionDate;}
set{_deletable.DeletionDate = value;}
}
public bool Deleted{get{return _deletable.Deleted;}}
public DateTime ModifiedDate {
// and so on as above
}

Related

How to hide non-generic method in generic interface if one inherits other [duplicate]

This is class design question.
I have main abstract class
public abstract class AbstractBlockRule
{
public long Id{get;set;}
public abstract List<IRestriction> Restrictions {get;};
}
public interface IRestriction{}
public interface IRestriction<T>:IRestriction where T:struct
{
T Limit {get;}
}
public TimeRestriction:IRestriction<TimeSpan>
{
public TimeSpan Limit{get;set;}
}
public AgeRestriction:IRestriction<int>
{
public int Limit{get;set;}
}
public class BlockRule:AbstractBlockRule
{
public virtual List<IRestriction> Restrictions {get;set;}
}
BlockRule rule=new BlockRule();
TimeRestriction t=new TimeRestriction();
AgeRestriction a=new AgeRestriction();
rule.Restrictions.Add(t);
rule.Restrictions.Add(a);
I have to use non-generic Interface IRestriction just to avoid specifying generic type T in main abstract class. I'm very new to generics. Can some one let me know how to better design this thing?
Your approach is typical (for example, IEnumerable<T> implements IEnumerable like this). If you want to provide maximum utility to consumers of your code, it would be nice to provide a non-generic accessor on the non-generic interface, then hide it in the generic implementation. For example:
public abstract class AbstractBlockRule
{
public long Id{get;set;}
public abstract List<IRestriction> Restrictions { get; set; }
}
public interface IRestriction
{
object Limit { get; }
}
public interface IRestriction<T> : IRestriction
where T:struct
{
// hide IRestriction.Limit
new T Limit {get;}
}
public abstract class RestrictionBase<T> : IRestriction<T>
where T:struct
{
// explicit implementation
object IRestriction.Limit
{
get { return Limit; }
}
// override when required
public virtual T Limit { get; set; }
}
public class TimeRestriction : RestrictionBase<TimeSpan>
{
}
public class AgeRestriction : RestrictionBase<TimeSpan>
{
}
public class BlockRule : AbstractBlockRule
{
public override List<IRestriction> Restrictions { get; set; }
}
I also showed using a base restriction class here, but it is not required.
The runtime treats IRestriction<TimeSpan> and IRestriction<int> as different distinct classes (they even have their own set of static variables). In your case the only classes common to both IRestriction<TimeSpan> and IRestriction<int> in the inheritance hierarchy are IRestriction and object.
So indeed, having a list of IRestriction is the only sensible way to go.
As a side note: you have a property Limit in there that you might want to access regardless of whether you're dealing with an IRestriction<TimeSpan> or IRestriction<int>. What I would do in this case is to define another property object Limit { get; } on IRestriction, and hide it in the actual implementation. Like this:
public interface IRestriction
{
object Limit { get; }
}
public interface IRestriction<T> : IRestriction
where T : struct
{
new T Limit { get; set; }
}
public class TimeRestriction : IRestriction<TimeSpan>
{
public TimeSpan Limit { get; set; }
// Explicit interface member:
// This is hidden from IntelliSense
// unless you cast to IRestriction.
object IRestriction.Limit
{
get
{
// Note: boxing happens here.
return (object)Limit;
}
}
}
This way you can access Limit as object on all your IRestriction when you don't care what type it is. For example:
foreach(IRestriction restriction in this.Restrictions)
{
Console.WriteLine(restriction.Limit);
}
Interfaces are contracts that need to be followed by the entity that implements the contract.
You have created two contract with the same name IRestriction
As far as I can see, what you are basically may need is a flag for classes that can be restricted, which should implement the IRestriction non-generic interface.
The second interface seems to be restrictable objects that also contain a limit property.
Hence the definition of the second IRestriction interface can be ILimitRestriction or whatever name suits your business needs.
Hence ILimitRestriction can inherit from IRestriction which would mark classes inheriting ILimitRestriction still objects of IRestriction
public abstract class AbstractBlockRule
{
public long Id{get;set;}
public abstract List<IRestriction> Restrictions {get;};
}
public interface IRestriction{}
public interface IRestrictionWithLimit<T>:IRestriction where T:struct
{
T Limit {get;}
}
public TimeRestriction:IRestrictionWithLimit<TimeSpan>
{
public TimeSpan Limit{get;set;}
}
public AgeRestriction:IRestrictionWithLimit<int>
{
public int Limit{get;set;}
}
public class BlockRule:AbstractBlockRule
{
public virtual List<IRestriction> Restrictions {get;set;}
}

every entity implement interface?

Currently, am working on architecture of application, I have many entities in my project i.e student teacher university, I was wondering about is it a good practice that all entity must implement interface. This will help me in dependency injection? What is the best practice from architecture point of view.
public interface IMyEntity
{
//an empty interface
}
public class Student:IMyEntity
{
}
public class Teacher:IMyEntity
{
}
//hi I can deal with every object which implement IMyEntity
void Display(IMyEntity entity) //this function can be in some class
{
// if IMyEntity is teacher behave like a teacher
// if IMyEntity is student behave like sutdent
}
I know interface is a contract, but from architecture point of view it is best practice? I know my IMyEntity interface is empty.
Not necessarily. If in this case Student and Teacher have some common functionality then a shared interface would be one approach to take.
public void Display(IUniPerson person)
{
var name = person.Name; // Everyone, student or teacher, has a name
...
}
However, the example you give seems to suggest that this is not the case, and the Display method will attempt to treat the passed in instance of IMyEntity differently depending on it's type. In that case, you may be better with 2 Display methods with different parameters.
public void Display(ITeacher teacher) { // teacher processing }
public void Display(IStudent student) { // student processing }
tl:dr version: implement an interface across multiple classes if it makes sense for those classes to implement related methods and functions, rather than just as a blanket rule.
I think that decoupling 2 or more classes is a good taste in terms of developing and it really helps maintaining the code in a long run.
Consider the follow scenario:
static void Main(string[] args)
{
var objA = new A();
var objB = new B(objA);
}
public class A {}
public class B
{
public B(A obj)
{
//Logic Here
}
}
The problem with this code it's that it's strongly coupled, class B needs class A to be instanced and do it's business.
This is not a problem if you are sure that B is never going to have some drammatic change.
Now if we want to decouple it we can make a first improvement implementing an interface like
static void Main(string[] args)
{
var objA = new A();
var objB = new B(objA);
}
public interface IA()
{
//TODO
}
public class A : IA {}
public class B
{
public B(IA obj)
{
//Logic Here
}
}
It looks quite better what we still have a couplation problem in the Main, so at this point we will have to implement a Dependency Injection with a IOC like Ninject, and our code will be like to something like:
static void Main(string[] args)
{
var objB = new B();
}
public interface IA()
{
//TODO
}
public class A : IA {}
public class B
{
public B(IA obj)
{
//Logic Here
}
}
Yes, that looks good. We have completely removed the couplation problem and it will be quite easy if in the future we just need to take A, delete it and replace it wich something new more cool.
Obviously overkilling it's a bad practice and I belive DI must be used only after carefuly planning to avoid useless implementations.
For example if I have a class C which has some basic operations, and I am sure that it will never change or have some drammatic need to update i can avoid DI.
So do you have to implement interfaces on every model in your project?
Well I don't think each model in your project needs to implements an interface or DI, just think about it and see where it can be useful and where it's just overkilling.
Looking at how .NET solved this, you can see some ambiguity.
For instance for every object has a function where you can ask for a string representation of the object: ToString(), even though for a string representation might not be a meaningful thing for a lot of classes
On the other hand, although it would be a useful function for every object to make a clone of itself they decided not to let every class implement ICloneable.
Whether it is wise for you to have (almost every) objects of your application a common interface depends on what you will do with this interface and the advantage of all objects implementing such an interface versus the burden of being obliged to implement the interface.
For example, if the entities you are talking about are database records, then it is very likely that every class will have some kind of ID. You could consider giving every class an interface with one get property that returns the value of the ID of the record.
public interface IID
{
long ID {get;}
}
The advantage are multifold:
You encourage every designer of database classes to implement the same type of primary key (in this case a long), and the same property name
Advantage: it is easier to spot the ID of a record
Advantage: it is easier to change the type of the ID
Advantage: you know if you have a database record, you know some of the functions the record must have, without really knowing the type of the record.
Even if the designer needs a different type, or different name, he can still create a special function to implement the interface:
public class Person : IID
{
public int ID {get; set;}
IID:ID {get {return this.ID;} }
}
However, I suggest not to force interfaces to object for which it is not natural to have them. This has the advantage that you can't use these strange functions for object that have no real usage for them.
For example, most classes that represent some ordered numerical value have some notion of addition. Not only for integers and real numbers, but also for classes that represent a time span: 4 days and 23 hours + 1 day and 7 ours = 6 days and 6 hours. So for a time span addition is a useful interface
However, for a date, addition is not meaningful: 4th of july + 14 juillet = ?
So: Yes, implement interfaces for items that are natural to them. They force common naming and enable reuse. No, don't implement them for items that do not have a natural meaning for the functions.
Yes do it like this, it is the best practise. This gives you the advantage of polymorphism. You should do it in better way in current context is not good, because Student is not a Teacher. If you want to share common interface you should define it as: IUniversityMember. Here an example for your case which I think will make it clear.
public interface IUniversityMember
{
//... here common fields between `Teacher` and `Student`
string Name{ get; set;}
string Gender { get; set;}
}
//after that
public interface IStudent
{
int GetGPA();
int CreditsToPass {get; private set;}
}
public interface ITeacher
{
int WorkedHours {get; set;}
decimal PayPerHour {get; private set;}
}
public class BiologicalStudent: IUniversityMember, IStudent
{
public int CreditsToPast {get; private set;}
public BiologicalStudent ()
{
CreditsToPast = 5;
}
//stuff
public int GetGPA()
{
return 3;
}
}
public class MathStudent: IUniversityMember, IStudent
{
public int CreditsToPast {get; private set;}
public BiologicalStudent ()
{
CreditsToPast = 9;
}
public int GetGPA()
{
return 2;
}
}
public class BiologicalTeacher: IUniversityMember, ITeacher
{
public int WorkedHours { get; set;}
public decimal PayPerHour {get; private set;}
public MathTeacher()
{
PayPerHour = 8;
}
}
public class MathTeacher: IUniversityMember, ITeacher
{
public int WorkedHours { get; set;}
public decimal PayPerHour {get; private set;}
public MathTeacher()
{
PayPerHour = 10;
}
}
//Now if you have a university class
public class OxfordUniversity:IUniversity //can inherit interface too
{
public int MinGAPForSchollarship {get; private set;}
public OxfordUniversity()
{
MinGAPForSchollarship = 3;
}
public decimal PaySallary(ITeacher teacher)
{
return teacher.WorkedHours*teacher.PayPerHour;
}
public bool CheckForSchollarship(IStudent student)
{
int gpa = student.GetGPA();
//do some checks
if(gpa >= MinGAPForSchollarship)
return true;
return false;
}
}

Implement common behaviour in alternative to abstract base classes?

In C#, I have a class hierarchy with a couple of abstract base classes near the top and a fair number of derived classes. A few these concrete classes have some common properties and methods that are implemented identically. It strikes me as wasteful and so one solution might be to implement this common behaviour in another abstract base class.
abstract class Control;
abstract class SquareControl: Control
{
public int SquarishProperty;
public void SquarishMethod();
};
class Window: SquareControl;
class Button: SquareControl;
However, what if several other classes in the hierarchy shared some other behaviour but also share something in common with one of the controls from another base class? Perhaps there are lots of areas of commonality. It would become impractical to model this with abstract base class implementation wouldn't it?
abstract class FlashableControl: Control
{
public int FlashyProperty;
public void FlashMethod();
};
class StatusBar: FlashableControl; // but it's also a bit square too, hmm...
So how do you go about sharing such implementations across classes without using base classes?
I imagine I want to delegate the implementaion of an interface to another class and have that class implement those properties and methods on behalf of the desired classes, so that to the user, the StatusBar and Window appear to support a standard interface, but under the covers it's something else that implements it.
I can visualise aggregating classes that implement this behaviour, but is this appropriate and are there any pitfalls? What are the alternatives?
Thanks
You can use a pattern like this:
public interface ICommonServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
public static class CommonServiceMethods
{
public static void DoSomething(this ICommonServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
All classes that implement ICommonServices now also get some free behavior via the extension method, which depends solely on those features exposed by all ICommonServices implementers. If you need access to base class functionality, you can put that in its own interface and have ICommonServices implement that interface as well. Now you can create 'default' extension functionality for interfaces without having to use multiple base classes.
EDIT
If you want some of these methods to be internal, you can modify the pattern like this:
public class MyObject : IServices
{
public string PublicProperty { get; private set; }
string IServices.SomeProperty { get; set; }
void IServices.SomeMethod(string param)
{
//Do something...
}
}
public interface IPublicServices
{
string PublicProperty { get; }
}
internal interface IServices : IPublicServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
internal static class ServiceMethods
{
public static void DoSomething(this IServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
Basically we're exposing both public and internal interfaces. Note that we implement the internal interface methods explicitly, so that the methods are not available for public consumption (since the public client can't get access to the interface type.) In this case, the helper extension methods are internal, relying on the internal interface, though you could also create public helper methods that rely on the public interface.
You could use 'has-a' instead of 'is-a' and delegate to an internal square control
class Window : Control, ISquareControl
{
private SquareControl square;
public void SquareOperation()
{
square.SquareOperation();
}
}
class SquareControl : Control, ISquareControl
{
public void SquareOperation()
{
// ...
}
}
One way is to use Interfaces and Base Classes.
Flashable would make a good Interface instead of a class.

Interface injection

Is it possible to inject an interface into an existing 3rd party class that I can not alter? Like extension methods but for an interface (and its implementation for the class that it had been injected to).
I like to optionally use one of two similar 3rd party libraries by giving classes that are similar in both libraries the same interfaces. So that I do not have to convert there classes into mine.
I don't completely understand what you mean about injecting an interface, but you could use the Adapter pattern to achieve this. See also: http://dofactory.com/Patterns/PatternAdapter.aspx
Create your own interface, then create your own classes that implement the interface, which contain/wrap the 3rd party classes.
As long as you're dealing with interfaces, why not just go with wrapping the classes in your own classes, that implement the interfaces?
You should look at the Decorator Pattern which allows you to extend a class by composition.
e.g.
Given sealed class A which implements InterfaceA:
public interface InterfaceA
{
int A {get; set;}
}
public sealed Class A : InterfaceA
{
public int A {get;set;}
}
You could extend InterfaceA and then use a decorator class B to encapsulate an instance of class A and provide additional methods.
public interface MyExtendedInterfaceA : InterfaceA
{
int B {get;set}
}
public class B : MyExtendedInterfaceA
{
private InterfaceA _implementsA = new A();
public int A
{
get
{
return _implementsA.A;
}
set
{
_implementsA.A = value;
}
}
public int B {get; set;}
}
Alternatively, decorator Class C could add a whole new interface:
public interface InterfaceC
{
int MethodC();
}
public class C : InterfaceA, InterfaceC
{
private InterfaceA _implementsA = new A();
public int A
{
get
{
return _implementsA.A;
}
set
{
_implementsA.A = value;
}
}
public int MethodC()
{
return A * 10;
}
}

c# - cast generic class to its base non-generic class

I have following classes:
public abstract class CustomerBase
{
public long CustomerNumber { get; set; }
public string Name { get; set; }
}
public abstract class CustomerWithChildern<T> : CustomerBase
where T: CustomerBase
{
public IList<T> Childern { get; private set; }
public CustomerWithChildern()
{
Childern = new List<T>();
}
}
public class SalesOffice : CustomerWithChildern<NationalNegotiation>
{
}
The SalesOffice is just one of few classes which represent different levels of customer hierarchy. Now I need to walk through this hierarchy from some point (CustomerBase). I can't figure out how to implement without using reflection. I'd like to implement something like:
public void WalkHierarchy(CustomerBase start)
{
Print(start.CustomerNumber);
if (start is CustomerWithChildern<>)
{
foreach(ch in start.Childern)
{
WalkHierarchy(ch);
}
}
}
Is there any chance I could get something like this working?
The solution based on suggested has-childern interface I implemented:
public interface ICustomerWithChildern
{
IEnumerable ChildernEnum { get; }
}
public abstract class CustomerWithChildern<T> : CustomerBase, ICustomerWithChildern
where T: CustomerBase
{
public IEnumerable ChildernEnum { get { return Childern; } }
public IList<T> Childern { get; private set; }
public CustomerWithChildern()
{
Childern = new List<T>();
}
}
public void WalkHierarchy(CustomerBase start)
{
var x = start.CustomerNumber;
var c = start as ICustomerWithChildern;
if (c != null)
{
foreach(var ch in c.ChildernEnum)
{
WalkHierarchy((CustomerBase)ch);
}
}
}
You could move the WalkHierarchy method to the base class and make it virtual. The base class implementation would only process the current node. For the CustomerWithChildern<T> class, the override would do an actual walk.
Try this:
if(start.GetType().GetGenericTypeDefinition() == typeof(CustomerWithChildern<>))
I believe that you want to make the lookup for the determination of doing to the walk an interface.
So maybe add an "IWalkable" interface that exposes the information needed to do the walk, then you can create your method checking to see if the passed object implements the interface.
"Is" and "As" only work on fully qualified generic types.
See this MSDN discussion for details including workarounds.
The most common workaround I've seen is to add an interface to the mix that your CustomerWithChildren could implement, and check for that interface.
I think everyone hits this "issue" when first working with generic classes.
Your first problem is hinted at in your question phrasing: an open generic type is NOT the base class to a closed one. There is no OO relationship here, at all. The real base class is CustomerBase. An "open" generic type is like a half-completed class; specifying type arguments "closes" it, making it complete.
While you can do:
Type t = typeof(CustomerWithChildern<>)
the condition
typeof(CustomerWithChildern<>).IsAssignableFrom(CustomerWithChildern<Foo>)
will always be False.
-Oisin
Explicitly with that method, no. However you can achieve the same functionality with an interface. In fact, you could just have your generic class implement IEnumerable. It's also worth noting that your class should also have "where T : CustomerBase" in order to ensure type safety.

Categories

Resources