I am trying to replace derived instances in base class. It works for animals (simple usage of abstract class), but not with generics. The error is in SomeMethod. Is there any clean solution?
EDIT: With help of another interface it is truly doable. Code that is commented with [S] is solution for my original question.
public abstract class Animal
{
public void Feed()
{
}
}
public class Tiger:Animal
{
}
public class Dog : Animal
{
}
public class Consumer
{
public Tiger Tiger { get; set; }
public Dog Dog { get; set; }
public Animal FavoriteAnimal { get; set; }
void SomeMethod()
{
// This is fine
FavoriteAnimal = Tiger;
FavoriteAnimal = Dog;
FavoriteAnimal.Feed();
//Also fine
int numberOfDogs = PlaceForDogs.CountAnimals();
int numberOfTigers = PlaceForTigers.CountAnimals();
//[S] This is doable now
FavoritePlaceForAnimals = PlaceForDogs;//[S] no more ERROR
int numberOfAnimalsOnMyFavoritPlace = FavoritePlaceForAnimals.CountAnimals(); // No error, but I do not get here...
}
public PlaceForDogs PlaceForDogs { get; set; } = new PlaceForDogs();
public PlaceForTigers PlaceForTigers { get; set; } = new PlaceForTigers();
//public PlaceForAnimals<Animal> FavoritePlaceForAnimals { get; set; }
//[S] favorite place is of type IPlaceForAnimals instead of PlaceForAnimals
public IPlaceForAnimals FavoritePlaceForAnimals { get; set; }
}
//[S]new interface
public interface IPlaceForAnimals
{
int CountAnimals();
}
//[S]abstract class implements the interface
public abstract class PlaceForAnimals<T>:IPlaceForAnimals where T : Animal
{
public List<T> Animals { get; set; }
public int CountAnimals()
{
//special counting using properties from Animal class
return 0;
}
}
A PlaceForAnimals<Dog> is not a PlaceForAnimals<Animal> (for purposes of assigning it that type), as it could not hold a tiger (while the original could).
The assignment is simply not legal without covariance. If you want to access certain methods you could have the base class implement a non-generic interface and make FavoritePlaceForAnimals be of that type.
The generic is wrapping a common set of functionality around a certain data type. Like List<int> functions the same as List<string>, it just gives you different data when you access it.
You could use a generic in the sense that your PlaceForAnimals<T> could have some defined behavior, but wrapped around a generic object like, say a Dog. But because it is just a wrapper around some functionality, it doesn't behave the same way as an inherited class like you have with your Animal superclass.
Inheritance lets you interchange data types, generics do not.
Related
I have a class structure like this:
BaseAnimal.cs:
public abstract class BaseAnimal
{
public string? Species { get; set; }
public double Price { get; set; }
}
Then I have this two classes:
public abstract class Carnivore : BaseAnimal
{
public double MeatFood { get; set; }
}
public abstract class Herbivore : BaseAnimal
{
public double GreenFood { get; set; }
}
And then I have the sub classes:
public class Ape : Herbivore
{
public Ape()
{
Species = "Ape";
GreenFood = 10.0;
Price = 10000.0;
}
}
Then I have a facotry which is already working with this line to get all the attributes from an animal:
public BaseAnimal[] Animals = prototypes.Values.ToArray();
And in my Main class I would like to read the properties of the Animals:
private void cboAnimals_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Debug.WriteLine(animalFactory.Animals[0].);
}
The problem with this code is, that I cannot access the properties specified in the Herbivore.cs and Carnivore.cs
What you should do is use Composition.
public interface IFood {
public double Food { get; set; }
}
public class Herbivore {
public double Food { get; set; }
}
public class Carnivore {
public double Food { get; set; }
}
public interface IAnimal {
string? Species { get; set; }
double Price { get; set; }
}
public class Animal {
string? Species { get; set; }
double Price { get; set; }
}
public class Ape {
private IAnimal _animal;
private IFood _food;
public Ape(IAnimal animal, IFood food) {
_animal = animal;
_food = food;
}
}
public void main(string[] args) {
IFood herbivore = new Herbivore(){Food = 10};
IAnimal ape = new Animal(){
Price = 1000;
Species = "Ape";
};
Ape ape = new Ape(ape, herbivore);
}
Now you can compose any class of type animal you want, you can reuse the implementation of IAnimal and IFood on other types, make new ones? Like Omnivore?
you can implement different species, and or "price" and load it into any new class like "dog" or "cat" you want, and compose that object with your Interfaces. Thus not needing to rewrite your tests, you don't need to have multiple implementations of say ... "Speak" on dogs that all do a "bark" you can have one class that does "bark" and then compose it into all dog like animals.
Just consider how easy it is now to implement a behaviour like "consume" that will work across all herbivores, omnivores or carnivores?
You only have to write 3 unit tests, one for each, not one for each animal type you eventually create, because they exist with dependency separation.
And Consume would work on any parameter of type food, so you don't even have to care if you find new ways of defining food, like a rock-eater or something :)
or if you had to descript plants, as something that "consumes" and you needed sunlight as a food source? Super simple to do, You wouldn't need to write x-amount of plant type unit tests for that either.
Composition over inheritance is by far the better choice to implement code in OOP.
Simplest is probably to check the type:
var foodAmount = animalFactory.Animals[0] switch {
Carnivore c => c.MeatFood ,
Herbivore h => h.GreenFood ,
_ => throw new InvalidOperationException()
};
But this is a typical example of inheritance taught in introductory programming. As a general rule, if you need to check the type, you might not have thought thru your type system well enough. The idea with inheritance is that everything implementation specific should be delegated to the implementation, so the user of the object do not need to know the concrete type.
I have some difficulty providing concrete recommendations since the example is so artificial, But I would recommend reading Eric Lippert series on Wizards and Warriors for a nice introduction to inheritance, and how people often do it wrong.
The problem is that animals array is of type BaseAnimal. You'll need to unbox it (ie cast it to it's subtype), you'll need some logic to check the type also, so something like
if (obj is Herbivore)
{
var herb = (Herbivore)obj;
herb.Greenfood= 123m;
}
It seems messy but at some point you need to get the concrete type.
Animals is an array of BaseAnimal. This class doesn't have a MeatFood or a GreenFood property. That's why you can't access these properties. If you could access them, this code would be possible:
BaseAnimal animal = new Ape();
Console.WriteLine(animal.MeatFood);
But Ape has no MeatFood property. If you want to access these properties, you have know whether your Animals[0] is a Carnivore or a Herbivore:
private void cboAnimals_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(animalFactory.Animals[0] is Carnivore carnivore)
{
Debug.WriteLine(carnivore.MeatFood);
}
else if (animalFactory.Animals[0] is Herbivore herbivore)
{
Debug.WriteLine(herbivore.GreenFood);
}
}
But maybe you realize at this point that you won't get good code by this. This is a sign that your class structure is not the best. In fact, why do you have two properties MeatFood and GreenFood? What is the difference between them? Both are of a double type. Hence maybe you should have a Food property in your BaseAnimal class and distinguish the type of food by an enum:
public enum FoodType
{
Meat,
Green
}
public abstract class BaseAnimal
{
public string? Species { get; set; }
public double Price { get; set; }
public double Food { get; set;}
public abstract FoodType FoodType {get;}
}
public abstract class Carnivore : BaseAnimal
{
public override FoodType FoodType{ get { return FoodType.Meat; } }
}
public abstract class Herbivore : BaseAnimal
{
public override FoodType FoodType{ get { return FoodType.Green; } }
}
I want to create a class that can take different types of value in a property. I am trying to do this using polymorphism, but I am not still learning how to do this properly, hence my request for advice.
I have a base class and two classes that inherit from it:
public abstract class BaseClass
{
public string Name { get; set; }
public Unit Unit { get; set; }
}
public class DerivedClassFloat : BaseClass
{
public float Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedClassString : BaseClass
{
public string Value { get; set; }
public override string ToString()
{
return Value;
}
}
All is good, I can create a List and add different specialized subclasses. My problem comes when I need change the values of the items in my list:
foreach (var item in ListOfBaseClasses)
{
if(item is DerivedClassFloat)
((DerivedClassFloat) item).Value = float.NaN;
if (item is DerivedClassString)
((DerivedClassString) item).Value = string.Empty;
}
According to what I have read, that looks like a code smell. Is there a better way to access the value property of my derived classes based on the type I am trying to assign?
What about when you want to create the right subclass based on the value?
BaseClass newClass = null;
if (phenotype is DerivedClassFloat)
newClass = new DerivedClassFloat(){Value = 12.2};
if (phenotype is DerivedClassString)
newClass = new DerivedClassString(){Value = "Hello"};
I read about overriding virtual methods, but that works if I want to process the value, not to add or change it … maybe I am missing something?
I should make this more concrete, my apologies, I am not used to post question in this great site.
I need a property that is made of a list of attributes. Each attribute has a name and a value, but the value can be of different types. For example:
public class Organism
{
public string Name { get; set; }
public List<Attribute> Attributes { get; set; }
}
public class Attribute
{
public string AttributeName { get; set; }
public object AttributeValue { get; set; }
}
For a given organism I can have several attributes holding different value types. I wanted to avoid using the object type so that I don’t have to cast to the right type. I though property polymorphism was the solution to handle this case elegantly, but then I found myself using If ..Then which didn’t seem too different from casting in the first place.
If in your particular case you want to reset Value, you can define an abstract ResetValue method in the base class, which will be implemented by the derives classes.
As for your second case, you should check out Creational Design Patterns, and specifically the Factory and Prototype design patterns.
You can use generics to define the type and the implementing subclass will set the Value type to the type constraint:
public abstract class BaseClass<T>
{
public string Name { get; set; }
public Unit Unit { get; set; }
public T Value { get; set; }
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedFloat : BaseClass<float> {}
public class DerivedString : BaseClass<string> {}
You can use Generics for this particular case:
public abstract class BaseClass<T>
{
public string Name { get; set; }
public Unit Unit { get; set; }
public T Value { get; set; }
}
public class DerivedClassFloat : BaseClass<float>
{
public override string ToString()
{
return Value.ToString();
}
}
public class DerivedClassString : BaseClass<string>
{
public override string ToString()
{
return Value;
}
}
Polymorphic behaviour works on abstraction. Based on what your trying to do, you can reduce code smell to moving as much of your variability in code to base classess.
i would suggest is instead of property write method like as follows. You can something like as follows.
public void setValue(string val, Type type);//move this to your base class
Class MyValue{
private string strVal;
private int intVal;
//constructor
MyValue(string val, Type type){
//check the type enum here and set the values accordingly
}
}
then when set values
foreach (var item in ListOfBaseClasses)
{
item.setValue = MyValue("",Type.INT);
}
I'm not quite sure what you are trying to achieve with this approach - the Value properties are not of the same type, there is also no Value property on the base class which suggests that other types derived from the base class might not have it at all.
If all of your classes require a Value property, then maybe it should be of the most general type object - you could put it onto the base class, but that would require casting the values in the derived classes.
But then you could have a NullObject to represent an absence of value that you could assign to the Value property for every derived class.
You can use the abstract factory pattern. Consider this example:
// Base class
class Button
{
protected Button()
{
}
public string Name { get; set; }
}
// Factory interface
public interface ButtonFactory
{
Button CreateButton();
}
// And the concrete classes
class WindowsButton : Button
{
// ...
}
class WindowsButtonFactory : ButtonFactory
{
public Button CreateButton()
{
return new WindowsButton();
}
}
class MacButton : Button
{
// ...
}
class MacButtonFactory : ButtonFactory
{
public Button CreateButton()
{
return new MacButton();
}
}
Furthermore, you can combine the abstract factory pattern with the strategy pattern to encapsulate the custom behaviors that change with type.
In a system for managing vocational training, I have a CourseBase abstract class, which I decided on using in favour of an ICourse interface because I'd prefer to avoid duplicating implementation code for all classes derived from the hypothetical, base Course entity. Each course has a list if subjects, with any subject defined by a SubjectBase abstract class. So, I have e.g.
public abstract class CourseBase : BaseObject
{
public IEnumerable<SubjectBase> Subjects
{
get { return new List<SubjectBase>(); }
}
}
public abstract class SubjectBase
{
public string Name { get; set; }
public string Description { get; set; }
public int ValidityPeriod { get; set; }
}
Now I want to add a concrete class, LocalCourse, which contains a collection of LocalCourseSubject objects, but because I'm not using an interface for CourseBase, I lose out on covariance, and I need to hide the abstract base's Subjects property with my new:
public class LocalCourse: CourseBase
{
public IEnumerable<LocalCourseSubject> Subjects
{
get { throw new NotImplementedException(); }
}
}
I'm sure I'm missing something very obvious here from an OO point of view, but the only solutions I can see are:
Completely omit Subjects from the abstract base, and only add a specifically typed collection property to derived classes.
Implement an interface such as ISubjectCollectionOwner in the abstract base as well as concrete classes.
Please excuse my dimness here, it's been a while since I've had the pleasure of encountering a design issue like this.
Why just not introduce a generic interface to abstract a Course? Sorry if I missed something obvious
public interface ICourse<TSubject>
{
IEnumerable<TSubject> Subjects { get; }
}
public abstract class CourseBase<TSubject>
: BaseObject,
ICourse<TSubject>
{
public IEnumerable<TSubject> Subjects
{
get { return new List<TSubject>(); }
}
}
public class LocalCourse
: CourseBase<LocalCourseSubject>
{
}
If Subject is a vital part of Course entity you should keep it within both ICourse and CourseBase as well, otherwise I would suggects abstracting it by ISubjectAware interface
Can't you just do this:
public abstract class CourseBase<T> where T : SubjectBase
{
public virtual IEnumerable<T> Subjects
{
get { return new List<T>(); }
}
}
public abstract class SubjectBase
{
public string Name { get; set; }
public string Description { get; set; }
public int ValidityPeriod { get; set; }
}
public class LocalCourse : CourseBase<LocalCourseSubject>
{
public override IEnumerable<LocalCourseSubject> Subjects
{
get { throw new NotImplementedException(); }
}
}
I think that would accomplish your short term goal, at any rate, assuming that the general pattern is that each CourseBase inheritor will have a collection of the same type of SubjectBase inheritor. But, if that is the case, this seems like a parallel inheritance hierarchy, which can sometimes be a code smell (not saying that it necessarily is -- I don't know all the details of the domain you're modeling).
I would like to force a set of classes to define three fields (of type string).
In an abstract class, I get that fields cannot be abstract and in an interface, I get an error saying that an interface cannot contain a field.
Is there no way to do this or am I not understanding this correctly? I'd rather not use methods because for some weird reason, the parentheses annoy me.
You can use properties for that:
interface MyInterface {
string Prop1 { get; set; }
string Prop2 { get; set; }
string Prop3 { get; set; }
}
Interface or abstract members force derived classes to provide code.
Fields don't have code.
You should use a property, which can be used like a field, but has code.
You can use Properties instead of fields:
// works similarly for Interfaces too
abstract class MyAbstractClass { public virtual string MyProperty1 { get; set; } }
class MyConcreteClass : MyAbstractClass { }
Then you can access MyProperty1 from any instance derived from MyAbstractClass:
MyAbstractClass obj1 = new MyConcreteClass;
obj1.MyProperty1 = "abcd";
Like everyone else says, use properties instead of fields, but you can do something like I interpreted in the comments as follows for read-only members:
abstract public class Base
{
abstract public string Foo { get; }
abstract public string Bar { get; }
abstract public string Baz { get; }
}
public class Derived : Base
{
public override string Foo { get { return "foo"; } }
public override string Bar { get { return "bar"; } }
public override string Baz { get { return "baz"; } }
}
If you want the fields to be modifiable later, you'll have to either use automatic properties or declare concrete backing fields and getter/setter pairs for each property.
I want:
public interface IBase
{
MyObject Property1 { get; set; }
}
public interface IBaseSub<T> : IBase
{
new T Property1 { get; set; }
}
public class MyClass : IBaseSub<YourObject>
{
public YourObject Property1 { get; set; }
}
But this doesn't compile. It gives the error:
//This class must implement the interface member IBase.Property1
Can anyone shed some light on this? I thought it should work..
Thanks
IBaseSub<T> requires IBase. I say "requires" because it more accurately reflects the practical implications than to say it "inherits" IBase, which implies overriding and other things that simply don't happen with interfaces. A class which implements IBaseSub<T> can actually be said to implement both, like so:
public class MyClass : IBase, IBaseSub<YourObject>
Going back to what I said about inheritance - there is no such thing with interfaces, which means just because both interfaces have a property with the same name, the derived one isn't overriding or hiding the base one. It means that your class must now literally implement two properties with the same name to fulfill both contracts. You can do this with explicit implementation:
public class MyClass : IBase, IBaseSub<YourObject>
{
public YourObject Property1 { get; set; }
MyObject IBase.Property1 { get; set; }
}
You need to implement the properties from both IBase and IBaseSub<YourObject>, since the latter expands on the former.
Using new in IBaseSub<T> does not let you "off the hook" regarding the necessity to have a MyObject Property1 { get; set; }. It simply allows you to declare another property named Property1 that implementors of IBaseSub<T> must have.
Since you cannot have two properties with the same name in MyClass, you will be forced to implement at least one of them explicitly:
public class MyClass : IBaseSub<YourObject>
{
MyObject IBase.Property1 { get; set; }
public YourObject Property1 { get; set; }
}