I am creating a game in Unity and I have 2 classes, I want to assign that variable with 2 different classes depending on a boolean value, to later use that class how I wish, here is the code I have so far to give an idea what im looking for, is it even possible for it to be done? Thanks
public GeneticController geneticController;
public GeneticDriver geneticDriver;
public Object Genetic;
void Start() {
if (RaceSelect.SelectedRace == 2) {
Genetic = geneticDriver;
} else {
Genetic = geneticController;
}
}
void FixedUpdate() {
float steer = (float)(Genetic.Steering);
Steering(steer);
}
At the moment It just says, that Object doesn't have a variable called "Steering". What type should Genetic be?
I am making some assumption here, that both GeneticController and GeneticDriver implement a Steering property? If so, and especially if they have additional properties and methods in common, the proper way to implement this is to refactor the classes so that they share a common interface.
public interface ISteering
{
float Steering {get; set;}
}
public class GeneticController : ISteering
{
public float Steering{ get; set; }
}
public class GeneticDriver: ISteering
{
public float Steering{ get; set; }
}
For there you can make your variable Genetic a type of ISteering.
public ISteering Genetic;
However, if Steering is the only property they have in common, I recommend you taking a second look at your overall design. If the two classes share no, or very little, common functions, they probably don't need to share a variable.
Have you tried using a base class that is derived into your 2 sub-classes?
Something along the lines of:
public class BaseClass
{
public float Steering {get;set;}
}
public class GeneticController : BaseClass
{
}
public class GeneticDriver : BaseClass
{
}
then you do the following (and you do not need the cast):
BaseClass Genetic
void Start()
{
if (RaceSelect.SelectedRace == 2)
{
Genetic = geneticDriver;
} else
{
Genetic = geneticController;
}
}
void FixedUpdate()
{
float steer = Genetic.Steering;
Steering(steer);
}
You could set the BaseClass as an interface also. It depends if you have common functionalities, or not, between you 2 derived classes.
Related
I am working on some project in Unity. I have:
[Serializable]
public class ItemAction
{
[SerializeField]
private UnityEvent unityEvent;
public void Perform()
{
unityEvent.Invoke();
}
}
[Serializable]
public class ItemAction<T>
{
[SerializeField]
private UnityEvent<T> unityEvent;
public void Perform(T parameter)
{
unityEvent.Invoke(parameter);
}
}
Also I have this class:
public abstract class Item : MonoBehaviour
{
[SerializeField]
private float weight;
[SerializeField]
private [collection of item actions] actions;
public abstract void Use();
public abstract void Grab(Transform transform);
public abstract void Drop();
}
How to create collection with mixed both generic and non-generic ItemAction instances (so some actions may require some parameters)?
For example:
For unequipped weapons, I can only grab them.
For unequipped medkits, I can grab them or use them immediately.
For triggers/switchers, I can only use them.
I could probably use an empty interface, but I don't think it's good solution...
Like you said you can create a empty interface or just use a collection of objects, because you will have to cast anyways or you skip the ItemAction class and only use the version which has a parameter and pass null for actions which don't require a parameter (not a "nice" solution either, but this is how the WPF framework does it with the ICommand interface, for example)
But there is an other problem, no matter if you use a interface or object list, you will not be able to show them in the editor (unless you create a custom editor), because the editor doesn't show generic classes.
Since you want to implement the methods in every specific item class inheriting from Item (at least, I guess so since you declared those methods abstract),
I'd go with another route, and implement interfaces for every specific action.
For example:
public interface IItem {
float Weight { get; set; }
}
public interface IGrabItem : IItem {
void Grab();
}
public interface IDropItem : IItem {
void Drop();
}
public interface IUseItem : IItem {
void Use();
}
public class MedKit : MonoBehaviour, IGrabItem, IUseItem {
[SerializeField]
float weight;
public float Weight {
get { return weight; }
set { weight = value; }
}
public void Grab() {
//Your code
}
public void Use() {
//Your code
}
}
and then you can choose to implement the code directly in every specific item class or use some kind of event to raise them.
Oh, and btw, if possible, avoid using UnityEvent and rely on the standard .NET event, it's faster and creates less overhead.
This should be a pretty straight-forward question. I only ask for a simple easy to understand answer. No, I don't want a textbook definition or a link to documentation, please, if possible answer this as simply as possible.
Consider the following:
class Monster
{
public int Hp { get; protected set; }
public string Name { get; protected set; }
public virtual void Attack()
{
Console.WriteLine("Monster attacking!");
}
}
class Skeleton : Monster
{
public Skeleton()
{
Hp = 20;
Name = "Skeleton";
}
public override void Attack()
{
Console.WriteLine("Skeleton attacking!");
}
}
Now imagine I create a new Skeleton object with the type Monster as so.
Monster skeleton = new Skeleton();
I would like to know the difference between creating a Skeleton object with a Monster Type vs creating a Skeleton Object with a Skeleton type.
Skeleton skeleton = new Skeleton();
I don't understand if there's a difference between the two or really how this works. Any and all help appreciated! Thank you!
The benefits to creating a Skeleton object with a Monster type becomes more apparent when you have multiple monsters that you want to hold in a single collection.
For example, you might have a list defined as follows:
List<Monster> EncounterMonsters = new List<Monster>();
Declaring your Skeleton object as Monster allows you to add it to this list, along with any other Monster classes you create.
So, you might have another monster class:
class Ogre : Monster
{
public Ogre()
{
Hp = 50;
Name = "Ogre";
}
public override void Attack()
{
Console.WriteLine("Ogre attacking!");
}
}
You could then do the following:
Monster skeleton = new Skeleton();
Monster ogre = new Ogre();
EncounterMonsters.Add(skeleton);
EncounterMonsters.Add(ogre);
This would then allow you to loop through the EncounterMonsters collection and attack with each using the overridden Attack method for each.
To Expand on the accepted answer, the difference is that if you instantiate your object using the base class Monster, only the properties and methods exposed by the Monster class are available.
Consider this:
public class Monster
{
public Monster(int hp, string name)
{
Hp = hp;
Name = name;
}
public int Hp { get; protected set; }
public string Name { get; protected set; }
}
public class Skeleton : Monster
{
public string Loot { get; set; } // <- Note added property.
public Skeleton(int hp, string name) : base(hp, name)
{
Loot = "Sword";
}
}
public class Vampire : Monster
{
//- some vampire specific properties
public Vampire(int hp, string name) : base(hp, name)
{
// ...
}
}
Now, if you instantiate your skeleton as a Monster.
Monster skeleton = new Skeleton(100, "skully");
skeleton.Loot(); //- Will throw a compile time error.
If you instantiate it as a Skeleton;
Skeleton skeleton = new Skeleton(100, "skully");
skeleton.Loot(); // Will return "Sword";
This is useful when you, for example, have a method or service that will act on common properties of your monsters, say you have a method that logs the stats of a monster.
public string LogMonsterStats(Monster monster)
{
return $"{monster.Name} has {monster.Hp} health points";
}
///....
Skeleton skeleton = new Skeleton(100, "Bob");
LogMonsterStats(skeleton); // returns "Bob has 100 health points"
Notice that we are passing a Skeleton instance to a method that expects a Monster instance. So within the scope of the method Bob is treated as a Monster, not as a Skeleton.
As we know that derive class can call base class constructor with help of "Base()" method.
initialize base class member
initialize subclass class member
We don't have facility to call derived call constructor from base class that is wrong approach.
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;
}
}
I created this interface:
public interface IPhrase
{
int CategoryId { get; set; }
string PhraseId { get; set; }
string English { get; set; }
string Romaji { get; set; }
string Kana { get; set; }
string Kanji { get; set; }
}
and this class:
public class Phrase : IPhrase
{
public Phrase()
{
}
public int CategoryId { get; set; }
public string PhraseId { get; set; }
public string English { get; set; }
public string Romaji { get; set; }
public string Kana { get; set; }
public string Kanji { get; set; }
}
Here this code returns data and typecasts it to Phrase:
var phrases = db2.Query<Phrase>("SELECT * FROM Phrase", ans);
var phrases = db2.Query<IPhrase>("SELECT * FROM Phrase", ans);
What I would like to know is if there is any difference / advantage in my using the IPhrase here or Phrase? Also what advantages are there (if any) in my creating a IPhrase interface in this example. Does that lead to more readable code?
An interface is a contract that guarantees, any class implementing the interface will implement the methods and properties defined in the interface. This allows you to use the interface to create methods, lists, etc. which accept any class that implements the interface e.g.
public interface IExample
{
int GetInt();
}
public void ProcessInt(IExample value)
{
var tempInt = value.GetInt();
// Do processing here
}
This allows any concrete class that implements interface IExample to be passed to this method. The method is assured that any concrete class passed will have the method GetInt implemented.
With objects you can inherit from to things:
Other Objects
Interfaces
Object
If you have an Animal object, a Dog object can inherit from it as it is an animal.
With Object inheritance think of the phrase: I am a ...._yourObject_...
Interface
With an interface you can think of it as a describer for that object. Such as IWalkOnTwoLegs or ICanSwim.
So think of the phrase : I can do ...._yourInterface_..
Now to answer your question, would it make a difference if you use an interface or not?
Well, it wouldn't in this case but if you extend your phrases and create a Question object and a Statement object, for example, and they inherit from Phrase, you have a choice where you can return all phrases (questions and statements) or only phrases that are Questions or only Statements.
You can also apply an interface saying IAmInFrench and IAmInSpanish to your phrase so you can have extended SpanishPhrase and FrenchPhrase objects.
Now you can return either all phrases whether they are questions, statements, in a different language, or you can be specific and return only french phases.
Where I find interfaces are most useful are for registration of different types in unity.
Where it will make a difference:
Where it will definitely make a difference is if there is a property on the object that isn't on the interface, then if you return the interface you will not be able to access that property very easily unless you type cast.
eg:
public class Phrase : IPhrase
{
public Phrase()
{
}
public int CategoryId { get; set; }
public string PhraseId { get; set; }
public string English { get; set; }
}
And interface
public interface IPhrase
{
int CategoryId { get; set; }
}
You will not be able to access the property English if you return the interface:
var phrases = db2.Query<IPhrase>("SELECT * FROM Phrase", ans);
var eng = phrases[0].English; //**THIS WONT WORK**
There is no difference between using an interface and a concrete object locally, as in your example. The main difference is when you are sending interfaces vs concrete classes as parameters in APIs or constructors parameters, where is preferably using interfaces so you can achieve decouple and testability.
Still for your question the short answer is no, there is no difference, whether you want to use interfaces or concrete objects as local variables is your own choice (what seems more readable to you). Do not forget that fields and properties are good to be declared as interfaces which provides more flexibility.
One last thing which should be considered when using a concrete object instead of an interface even locally is that you may want someday to change the signature of the method which provides you that object to return another kind of object which implements the same interface, and in that case you should change the local variable too (even if it's not so bad and it happens very rarely I had to note it), as in the following example:
interface IAnimal
{
void Run();
}
class Cat : IAnimal
{
public void Run()
{
//...
}
}
class Dog : IAnimal
{
public void Run()
{
//...
}
}
If in your code you have a method which returns a Cat that you use:
Cat GetAnimal()
{
return new Cat();
}
Cat myAnimal = GetAnimal(); //note that here it is expected a Cat
myAnimal.Run();
Then if you change the GetAnimal signature to return a Dog, your code should be changed in order to compile to:
Dog myAnimal = GetAnimal(); //note that here it is expected a Cat
myAnimal.Run();
But if you are using an interface there are less chances that your code will need to be changed when method's signatures ar changed:
IAnimal myAnimal = GetAnimal(); //this is working whether a Cat or a Dog is received.
myAnimal.Run();
But again this is happening relatively rarely. Sorry for the silly Cat & Dog example!
A class is a template for an object. It is essentially a blueprint. So for a light there a button that is on and off. Say when you call this method a value is sent to some controller that turns it on and off. All you have to do is call the method for on/off and viola it works.
An interface is very similar. Here the on/off method might not be implemented. You actually have to go and write the code to turn the light on and off but you must write the on/off method or it cannot be that interface. Say there is a new type of light that has dimming functionality. An interface allows you to implement this new feature for a different type of light. So its basically telling you that you have to have this stuff done (on/off) for it to be a light but we don't care how you implement it. Some parts of the interface may be implemented for you, but other parts you have to implement.
When would an interface make sense? A situation where you have many objects that are very similar in nature but differ slightly in implementation. For example say you have many types of shapes. Each is going to have an area. The calculation is different for a triangle than it is for a circle. Now say you have hundreds of shapes that need to be constructed, you wouldn't keep making new objects for each type of shape, you would just implement the interface. This gives somebody the power to create shapes, maybe even custom shapes, with similar methods but different implementations.
Your answer depends on the way you want to use your future classes. Interfaces are contracts to ensure descendant classes have all definitions of interface. So This is useful when you want to use polymorphism. in this way, you can define all common specifications of an object in an interface class. Another advantage of interfaces is that your class can inherit from multiple interfaces, which is not allowed for other type of classes in C#. Here is an example code. Hope to be useful for you:
public interface IShape
{
float Area { get; }
float circumference { get; }
}
public class Rectangle : IShape
{
private float l, h;
public Rectangle( float length, float height ) { l = length; h = height; }
public float Area { get { return l * h; } }
public float circumference { get { return ( l + h ) * 2; } }
}
public class Circle : IShape
{
private float r;
public Circle( float radius ) { r = radius; }
public float Area { get { return (float)Math.PI * r * r; } }
public float circumference { get { return (float)Math.PI * r * 2; } }
}
public class SomeClass
{
IShape[] shapes = new IShape[] // Can store all shapes regardless of its type
{
new Rectangle( 10f, 20f ),
new Rectangle( 15f, 20f ),
new Rectangle( 11.6f, .8f ),
new Circle( 11f ),
new Circle( 4.7f )
};
public void PrintAreas()
{
foreach ( var sh in shapes )
Console.WriteLine( sh.Area ); // prints area of shape regardless of its type
}
public void PrintCircumference(IShape shape )
{
Console.WriteLine( shape.circumference ); // again its not important what is your shape, you cant use this function to print its cicumference
}
}
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
}