I am working on a transportation problem and cannot leap this hurdle. I am unable to convert the derived class StopsVisited to its base class Stops. The base class Stops is a collection of Stop. The derived class StopsVisited is a collection of StopVisited.
The element StopVisited derives from Stop (definitions not shown).
I have a non-generics workaround where I simplly derive StopsVisited from Stops, but the generics afford me more felixibility. I've tried to reduce it to its simplest form.
Base
public abstract class Stops<T> where T : Stop
{
}
Derived
public class StopsVisited : Stops<StopVisited>
{
}
The problem:
Stops<Stop> stops = new StopsVisited();
Gives me a
Error 1 Cannot implicitly convert type 'StopsHeirarchy.StopsVisited' to 'StopsHeirarchy.Stops'
Any help is appreciated.
StopsVisited is not a subtype of Stops<Stop>; it's a subtype of Stops<StopVisited>, which is an entirely different thing. I agree with duffymo that subtyping is the wrong approach to your problem, but the specific feature you're asking about is called "covariance" or "output-safe" in C# 4; you can read about it here.
Personally, I wouldn't use inheritance to say that a Stop has been visited. I'd have a boolean data member to say that a Stop had been visited. It seems like a binary attribute - you've either been visited or you haven't.
Inheritance ought to be about different behaviors. Unless you can say that a visited Stop somehow behaves differently, I would advise against inheritance in this design.
C# 4.0 solves this problem by modifying the CLR to support it.
In the meantime, have an IStops interface (non-generic) and convert to it.
Related
I was doing my homework and got stuck in some problems with generics and inheritance.
I have a generic red-black tree class, since it's red-black tree its keys should be comparable, so
public class RedBlackTree<T> where T : IComparable<T>
And then I want another class, let's say, an interval tree, which is an augmented version of red-black tree. So I defined the interval like this:
public class Interval<T> : IComparable where T : IComparable<T>
and since interval tree is indeed a red-black tree with intervals as its keys but just with more specific methods, I defined the class like this:
public class IntervalTree<T> : RedBlackTree<Interval<T>> where T : IComparable<T>
But it won't let me do this, it says something like "cannot implicitly convert Interval<T> to System.IComparable<Interval<T>>", but I also can't write something like where Interval<T> : IComparable<Interval<T>>.
How would I do things like this in C#, or if there's no way to do this inheritance in C# what other templates should I use?
Let's take it apart. We'll stop using T for everything, because that gets confusing.
class RedBlackTree<RBTValue> where RBTValue : IComparable<RBTValue>
OK, so every RBTValue that is used to construct RedBlackTree<> must be an IComparable<RBTValue>.
You wish to say
RedBlackTree<Interval<T>>
for some T at some point. What do we then know? Interval<T> is being used for RBTValue, and therefore Interval<T> must be known to be IComparable<Interval<T>>.
Therefore the definition of Interval<> needs to be:
class Interval<IValue> : IComparable<Interval<IValue>>
Now, is it also the case that any IValue needs to be IComparable<IValue>? If yes, then we need a constraint:
class Interval<IValue> : IComparable<Interval<IValue>>
where IValue : IComparable<IValue>
Make sure this is clear. This is saying two things, (1) that an interval is comparable to another interval, and (2) that the values in an interval are comparable to other values.
Now we wish to define an interval tree.
class IntervalTree<ITValue> : RedBlackTree<Interval<ITValue>>
where ITValue : IComparable<ITValue>
Does this satisfy our needs? Interval<IValue> requires that IValue implement IComparable<IValue>. ITValue implements IComparable<ITValue> via the constraint, so the requirement is satisfied.
RedBlackTree<RBTValue> requires that RBTValue be IComparable<RBTValue>. Interval<ITValue> implements IComparable<Interval<ITValue>>, so that's also good, and we're all set.
That all said: you might consider instead implementing IntervalTree<> with an RBT as a member rather than as a base class. Is there ever a case where you are going to be treating interval trees polymorphically with red black trees? If not, there's no need to expose the implementation detail in the public surface.
Finally, these sorts of types can get very confusing. For some more thoughts on ways in which this pattern can be abused far more horribly, see
https://blogs.msdn.microsoft.com/ericlippert/2011/02/03/curiouser-and-curiouser/
The error you are getting is the following:
Compilation error (line xx, col yy): The type 'Program.Interval<T>'
cannot be used as type parameter 'T' in the generic type or method
'Program.RedBlackTree<T>'. There is no implicit reference conversion
from 'Program.Interval<T>' to
'System.IComparable<Program.Interval<T>>'.
You need to take the error apart and think about what it is telling you. In this case you are declaring that IntervalTree inherits from RedBlackTree<Interval<T>>. However, you have specified that the generic T type for RedBlackTree must implement IComparable<T>. If you implement IComparable for Interval the error will go away. Interval must implement the interface used to constrict RedBlackTree.
UPDATE:
Thanks to some help it seems to be a bug with Unity's compiler as it doesn't happen outside of Unity. I am currently submitting a bug report and I'll try and find a work around.
I originally posted this to reddit but I think I will need all the help I can get. Here is it copied over:
Not sure how it has come to this, but in order to maintain maximum extendability I have had to use all this techniques.
In short, this works
ICombatEffect<IEffectReturn> com = new TackleEffectBase(this);
but when I try this
ICombatEffect<IEffectReturn>[] EffectsArra = ICombatEffect<IEffectReturn>[]{new TackleEffectBase(this);}
or this
List< ICombatEffect<IEffectReturn>> EffectsList = new List< ICombatEffect<IEffectReturn>>{new TackleEffectBase(this)}
I get an ArrayTypeMismatchException.
Now for the details: (although I've condensed this a lot)
p
ublic interface ICombatEffect<out T> where T : IEffectReturn
{
T Effect(CombatProcessor combat);
}
public abstract class EffectTemplate<T1> : ICombatEffect<T1> where T1 : IEffectReturn
{
public abstract T1 Effect(CombatProcessor combat);
}
public abstract class DamageBaseTemplate : EffectTemplate<DamageBaseModifier>
{}
DamageBaseModifier : IEffectReturn
public class TackleEffectBase : DamageBaseTemplate
I've left out all of the functional stuff so I can let the types do the talking.
The premise is that I each ICombatEffect has an Effect Method. The Effect method must always have a return type that implements IEffectReturn interface. I need to preserve the return type of each ICombatEffect as it is used for sorting later.
Since I have quite a lot of functional code, I've put in the abstract class EffectTemplate. I've read a lot about this sort of style and the trick is to make the interface non-generic. I do not have that luxury unfortunately as sometimes I will not be using the template. So I have set up the interface with a covariant generic type. The abstract class sort of has its generic type linked so they will be the same. This took me a bloody long time to figure out and I was pretty disappointing when I couldn't get it to run today.
I'm no expert on generics but here is my theory on why I can create a single instance but not add that to a collection. When you declare the single instance it goes through and sets all the generics to the instance's type. For a collection, you can't really make its generics concrete, they are only there to see if it slots in.
I'm pretty ok with tearing this down for a better solution as long as it fulfills my needs, but I'm pretty darn curious about this solution. I thought myself so clever when I got all these cascading generic types to work, but alas.
Right now, I am learning OOP, mainly in c#. I am interested in what are the main reasons to make a class that can't be instantiated. What would be the correct example of when to make an abstract class?
I found myself using the abstract class in inheritance way too enthusiastically. Are there some rules when class is abstract in system and when class should not be abstract?
For instance, I made doctor and patient classes which are similar in some way so I derived them both from abstract class Person (since both have name and surname). Was that wrong?
Sorry if the question is stupid, I am very new at this.
There are a couple of things no one has pointed out so far, so I would just like to point them out.
You can only inherit from one base class (which could be abstract) but you can implement many interfaces. So in this sense inheriting an abstract class is a closer relationship than implementing an interface.
So if you later on realize that you have a need for a class which implements two different abstract classes you are in deep shit :)
To answer your question "when to make an abstract class" I'd say never, avoid it if possible, it will never pay off in the long run, if the main class is not suitable as a ordinary class, it probably isn't really needed as abstract either, use an interface. If you ever get in the situation where you are duplicating code it might be suitable with an abstract class, but always have a look at interfaces and behavioral patterns first (ex the strategy pattern solves a lot of issues people wrongly use inheritance to solve, always prefer composition over inheritance). Use abstract classes as a last hand solution, not as a design.
To get a better understanding of OOP in general, I'd recommend you to have a look at Design Patterns: Elements of Reusable Object-Oriented Software (a book) which gives a good overview of OO-design and reusability of OO-components. OO-design is about so much more than inheritance :)
For Example: you have a scenario where you need to pull data from different sources, like "Excel File,XML,any Database etc" and save in one common destination. It may be any database. So in this situation you can use abstract classes like this.
abstract class AbstractImporter
{
public abstract List<SoldProduct> FetchData();
public bool UploadData(List<SoldProduct> productsSold)
{
// here you can do code to save data in common destination
}
}
public class ExcelImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from excel
}
}
public class XMLImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from XML
}
}
public class AccessDataImporter : AbstractImporter
{
public override List<SoldProduct> FetchData()
{
// here do code to get data from Access database
}
}
and calling can be like this
static class Program
{
static void Main()
{
List<SoldProduct> lstProducts;
ExcelImporter excelImp = new ExcelImporter();
lstProducts = excelImp.FetchData();
excelImp.UploadData(lstProducts);
XMLImporter xmlImp = new XMLImporter ();
lstProducts = xmlImp.FetchData();
xmlImp.UploadData(lstProducts);
AccessDataImporterxmlImp accImp = new AccessDataImporter();
lstProducts = accImp .FetchData();
accImp.UploadData(lstProducts);
}
}
So, in Above example, implementation of data import functionality is separated in extended (derived) class but data upload functionality is common for all.
This is probably a non-academic definition, but an abstract class should represent an entity that is so "abstract" that make no sense to instantiate it.
It is often used to create "templates" that must be extended by concrete classes. So an abstract class can implement common features, for example implementing some methods of an interface, an delegate to concrete classes implementation of specific behaviors.
In essence what you have done is fine if you never want to instantiate a Person class, however as I'm guessing you may want to instantiate a Person class at some point in the future then it should not be abstract.
Although there is an argument that you code to fix current issues, not to cater for issues which may never arise, so if you need to instantiate Person class do not mark it as abstract.
Abstract classes are incomplete and must be implemented in a derived class... Generally speaking I tend to prefer abstract base classes over interfaces.
Look into the difference between abstract classes and interfaces...
"The difference between an abstract class and an interface is that an abstract class can have a default implementation of methods, so if you don't override them in a derived class, the abstract base class implementation is used. Interfaces cannot have any implementation." Taken from this SO post
As already stated, noone will force you to use abstract classes, it is just a methodology to abstract certain functionality which is common among a number of classes.
Your case is a good example where to use abstract classes, because you have common properties among two different types. But of cause it restricts you to use Person as a type by itself. If you want to have this restriction is basically up to you.
In general, I would not use abstract classes for Model like classes as you have unless you want to prevent Person from being instantiated.
Usually I use abstract classes if I also have defined an interface and I need to code different implementations for this interface but also want to have a BaseClass which already covers some common functionality for all implementations.
Deriving both 'Doctor' and 'Patient' from an abstract class 'Person' is fine, but you should probably make Person just a regular class. It depends on the context in which 'Person' is being used, though.
For example, you might have an abstract class named 'GameObject'. Every object in the game (e.g. Pistol, OneUp) extends 'GameObject'. But you can't have a 'GameObject' by itself, as 'GameObject' describes what a class should have, but doesn't go into detail as to what they are.
For example, GameObject might say something like: "All GameObjects must look like something'. A Pistol might extend on what GameObject said, and it says "All Pistols must look like a long barrel with a grip on one end and a trigger."
The key is whether instantiation of that class ever makes sense. If it will never be appropriate to instantiate that class, then it should be abstract.
A classic example is a Shape base class, with Square, Circle and Triangle child classes. A Shape should never be instantiated because by definition, you don't know what shape you want it to be. Therefore, it makes sense to make Shape an abstract class.
Incidentally, another issue which hasn't yet been mentioned is that it is possible to add members to an abstract class, have existing implementations automatically support them, and allow consumers to use implementations which know about the new members and implementations which don't, interchangeably. While there are some plausible mechanisms by which a future .NET runtime could allow interfaces to work that way as well, at present they do not.
For example, if IEnumerable had been an abstract class (there are of course good many reasons why it isn't), something like a Count method could have been added when its usefulness became apparent; its default implementation of Count could behave much like the IEnumerable<T>.Count extension method, but implementations which knew about the new method could implement it more efficiently (although IEnumerable<T>.Count will try to take advantage of implementations of ICollection<T>.Count or ICollection.Count, it first has to determine whether they exist; by contrast, any override would know that it has code to handle Count directly).
It would have been possible to add an ICountableEnumerable<T> interface which inherited from IEnumerable<T> but included Count, and existing code would continue to work just fine with IEnumerable<T> as it always had, but any time an ICountableEnumerable<T> was passed through existing code, the recipient would have to recast it to ICountableEnumerable<T> to use the Count method. Far less convenient than having a directly-dispatched Count method which could simply act directly on IEnumerable<T> [the Count extension method isn't horrible, but it's far less efficient than would be a directly-dispatched virtual method].
If there were a means by which an interface could include static methods, and if the class loader, upon finding that a class Boz which claimed to implement IFoo, was missing method string IFoo.Bar(int), would automatically add to that class:
stringIFoo.Bar(int p1) { return IFoo.classHelper_Bar(Boz this, int p1); }
[assuming the interface contains that static method], then it would be possible to have interfaces add members without breaking existing implementations, provided that they also included static methods that could be called by default implementations. Unfortunately, I know of no plans to add any such functionality.
I've got the code below and I'm trying to do some inheritance exercises but when I try to run this code it gives me an error:
Inconsistent Accessability: Base Class is less accessible than class
The code:
class Program
{
static void Main()
{
FoodProducts Test = new FoodProducts();
Test.Limit();
}
}
public class FoodProducts : Products
{
public void FoodProduct()
{
Console.WriteLine("This is food product");
}
public void Limit()
{
Console.WriteLine("This is an Attribute of a Product");
}
}
Would someone be able to help me?
What line is the error on, and what is the specific error text? Also, where is the definition of Products?
You are probably getting CS0060: "Inconsistent accessibility: base class 'class1' is less accessible than class 'class2'" Thus, I'm assuming your Products class is not marked as public.
This problem happens when a base class is marked as something other than public (internal, for example), but then you try to make a public derived class.
Just for future reference for someone thick like me, I got this in the following situation and couldn't figure out what was going wrong:
public class Foo : Base<Bar> {} <-- Inconsistent accessibility
public class Base<T> {}
It took me a while to work out that the culprit was here:
internal class Bar {}
Lots of answers here suggest to change your base class into public too. In a sense they are correct, but then they miss an equally valid alternative, which is to change your derived class to internal (to match what the base class's accessibility).
So, the real (yet short) answer is to let your base class and derived class to have same accessibility.
For those who wonder why, the long answer is: when a public derived class attempts to inherit an internal or private base class, it would argurably (more on this later) become semantically unclear whether the sub-class would also want to expose those public methods in the internal/private base class. Eric Lippert gave an detailed explanation in his blog post: Why is deriving a public class from an internal class illegal?, quoted below (with minor edit):
On the one hand, it is a public method of a base class, and so it seems like it should be accessible (to the derived class too). On the other hand, the fact that Base is internal is evidence that its internal method is supposed to be inaccessible outside the assembly. A basic design principle of C# is that when the intention is unclear, the compiler brings this fact to your attention by failing.
PS: That being said, one may argue that, the compiler could possibly just stick with "one of those 2 hands" and it would still be deterministic. So why was the design decision NOT chosen on one specific way? For such a follow-up question, the answer is, it all boils down to design philosophy that (again, quoted from Eric's blog post):
this rule of the language encourages you to use inheritance relationships to model the business domain semantics rather than as a mechanism for code reuse.
So that was the choice C# already made.
Lastly, for the sake of completeness, it is worth to mention that, the design philosophy above is not necessarily the universal and only way to use inheritance. (Heck, some other languages do not even have the public/internal concept in the first place and they are still successful). Personally I see nothing wrong if we would also want to use inheritance mechanism for code reuse. But C# already chose to only use inheritance for business domain semantics. So, it is what it is.
Probably the class Products is not public. Add public to the Products class definition.
If you have something like:
class Products {
...
}
The C# compiler interprets the Products class as internal.
Add the public directive to the class you are trying to inherit from.
public class Products
Make you class public(as shown above) in order for it to be inherited or accessible.
You can also add this before the definition of the namespace in your base class (right after the last "using ..." line):
[assembly: InternalsVisibleTo("<name of the assembly of the caller class>")]
That happens when, for example, the base class is private, but the derived class is public. A contradiction, so to speak.
this means if you wish a public child class, the parent class must be public also.
One of the probable reason for this issue may be , you have more than one main class , Make sure you have only one main class.
A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a abstract enum in the base class to be used for checking the type of the subclass, or if you should use the is operator.
Alt 1.
public abstract class Document{
}
public class PDF:Document{
}
Check: If (myobj is PDF)
Alt 2.
public abstract class Document{
public abstract DucumentType TypeOfDocument {get;}
}
public class PDF:Document{
public DucumentType TypeOfDocument { get{return DucumentType.PDF };}
}
public enum DucumentType{
PDF, Word
}
Check: If (myobj.TypeOfDocument == DucumentType.PDF)
The ones for Alt1. ment that Alt2 slightly breaks SRP, you don’t take advantage of OO, Your repeating the abstraction. Since inheritance is the hardest connection between classes you cannot avoid knowing of them, and if you must go thru with inheritance minimize the impact. Alt2 also breaks DRY
The ones for Alt2 ment that Alt2 will be removing type checking entirely and replacing it with the option of checking this enum instead. Removing all hard connections to all subclasses, and the value of the enum itself does not say anything about which concrete implementation thats currently beeing operated on.
Whats your opinion about the two alternatives?
No discussion of inheritance vs. composition etcetera, that’s another question!
Why do you need to know in the first place? I agree that it's occasionally necessary, but where possible you should make the Document type have appropriate abstract functionality to allow the specialization to be done through inheritance rather than the caller having to treat it differently.
I would only use the enum approach if different subclasses may share document types but withotu wanting to share an inheritance hierarchy. This would be pretty rare, IME.
IMO you should use the is operator.
It gives you the same result without tainting the (abstract) class code.
I've got a similar situation, except that in my case, the DocumentType enum needs to grow as various types are added. By using the Enum, type checking is much better, but it requires that the "generic" base class be recompiled every time a new DocumentType is added.
The alternative I'm currently pondering is to use an interface property to return the type as a STRING. It's not great for type checking, but the rest of my code has the necessary validation to prevent rogue DocumentType objects. I would prefer a different solution, but nothing comes to mind.