I have two classes, one which inherits the other, for example:-
public class A
{
public string AA { get; set; }
public double AB { get; set; }
}
and
public class B : A
{
public double? BA { get; set; }
}
Now, I know that if I have an instance of object B, I can cast that as type A, but I have an instance of A that I want to instantiate as a type B object. I know I could put a constructor in B's class which copies all the property values over, but the base class, A, has quite a few properties and may well have more added, so I'm worried about missing one or forgetting to add it in to B's constructor when I add it to A. Is there an easy way of doing this, please?
-------Edit------
Thanks folks, not my use-case unfortunately, it's a question a mate's fired at me. As far as I'm aware there are issues and he can't change the base class. As I understand it, the base class is one that hooks into a database call, he then wants to grab that data and add some extra properties for an admin editing screen which his code will then use to update the base data object's properties. My first reaction was to have the base object as a property of his object, but there's a reason it's significantly easier for him to have it "flattened" with the tools he's using. I didn't think there was a way of doing this, but I thought I'd check in case I was missing something - I thought it would be easier to just ask the basic question, rather than include the background, which would probably just raise more questions and muddy the water (AFAIK he's suffering from "circumstances beyond his control", with this).
I know I could put a constructor in B's class which copies all the property values over, but the base class, A, has quite a few properties and may well have more added, so I'm worried about missing one or forgetting to add it in to B's constructor when I add it to A. Is there an easy way of doing this, please?
Typically, this is a sign of a design flaw. I would rethink your design first, and determine whether this is truly necessary, or if there is another approach you can use here. That being said...
There is no easy way to do this. If you need a B instance to be created from your A instance, you'll really need to copy the values over to the new instance.
A better option, however, would potentially be to add a (potentially protected) constructor to A that sets all of these properties, given another A instance. B could then use this to create itself, which at least keeps the requirements for matching all of the properties within the class that defines them. This should make it easier to maintain this over time.
I agree with the other remarks, you're better off using a different design, such as composition instead of inheritance.
Composition, shown below, allows you to modify class A without requiring any changes to class B.
public class B
{
// Constructor
public B(A A) { this.A = A; }
// Class A as a read-only property
public A A { get; private set; }
// Other properties of class B
public double? BA { get; set; }
}
Reverse Polymorphism is not supported in c#.
As Reed Copsey said, this is typically a sign of a design flaw. I would re-work the class diagram if you need something like this to work. It sounds like some sort of mistake was made in the inheritance architecture somewhere.
If all you need is for both child and parent to implement common methods so that when either of the objects is passed to some function it can operate on some common methods on the passed-in object, then just have the two of them implement the same interface (polymorphism), or type the function parameter as the base class and make sure the methods exist on the base class.
Related
We have a system that creates dynamically defined objects as a core aspect of the processing. I would like to be able to create an class object and make these objects instances of this class, implementing all of the functionality that this particular object has.
The problem is, these objects really need to dynamically inherit from a base class, and override null methods etc. In essence, I need something of a dynamic class structure (and I have proposed compiling the definitions into a proper class model, but that is some distance away). The best approach i can come up with is to create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented.
I have also looked at Castles DynamicProxy approach, which might be a useful route (intercepting the calls and actioning them if appropriate), but this seems more complex than it should be.
So any suggestions? What would the best, most .Net-like approach to this be? As I look at the problem, it seems like there should be a really good and easy solution.
Just to help, a simple example (semi-pseudocode - I know it is not fully working):
class thing
{
public void Process()
{
foo();
bar();
}
private foo(){}
private bar(){}
}
a=new thing() {foo=DoFoo}
b=new thing() {bar=DoBar}
I want to be able to call a.Process and b.Process, and have them both run. Bear in mind that these objects have some 20-30 properties/methods that might need setting (setting them is easy, but some of them might be substantial methods)
create a class instance with a set of blank properties, and dyamically replace these properties with methods if these features are implemented
This sounds a lot like the "decorator" design pattern might be a good choice for you here. You basically implement a set of functionalities and then build your objects by subsequently assigning several "decorations" (functionalities) to a baseobject.
http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp seems to be a very good summary with clear examples on how and when to use decorator patterns
However if your properties heavily interact with each other, or need a significant different implementation depending on other "decorations" i would not suggest using a decorator. In that case you might need to get a bit more specific on your requirements.
Not sure if I really understand your requirements, but have you looked at the DynamicObject class?
The idea behind it is that you derive from it, and every time a member is accessed, it gets a call to TryGetMember, TrySetMember, or TryInvokeMember for methods, where you can do your custom logic.
You can make a base class inheriting from DynamicObject then make the set of classes you want by deriving from that base class, implementing the logic on each one of them, this way you can have both defined members, and other non-defined ones which you can use using a dynamic type.
Check the documentation on MSDN for DynamicObject
Alternative
Otherwise, as a very simple solution and based on the pseudo-code you provided only (which admittedly might be a little simple for the requirements stated in the question), you could just make a Thing class which has Action properties:
class Thing
{
public void Process()
{
if(Foo!=null) Foo();
if(Bar!=null) Bar();
}
public Action Foo {get;set;}
public Action Bar {get;set;}
}
var a=new Thing() {Foo=DoFoo};
var b=new Thing() {Bar=DoBar};
a.Process();
b.Process();
I have a property in a base class that I don't want overridden for any reason. It assigns an ID to the class for use with a ThreadQueue I created. I see no reason whatsoever for anyone to override it. I was wondering how I can block anyone from attempting to override it short of them changing its modifier.
private int _threadHostID = 0;
public int ThreadHostID
{
get
{
if (_threadHostID == 0)
{
_threadHostID = ThreadQueue.RequestHostID();
}
return _threadHostID;
}
}
Edit: totally forgot the language: C#.
Edit2: It is not virtual or overriding anything else so please no sealed.
First off: "Overriding" refers to virtual overriding. You are talking about creating hiding methods, not overriding methods.
I have a property in a base class that I don't want hidden
You are free to want that, but you are going to have to learn to live with the disappointment of not getting what you want.
I see no reason whatsoever for anyone to hide it.
Then there won't be a problem, will there? If no one could possible want to hide it, then they won't hide it. You're basically saying "I have an object of no value to anyone; how do I keep someone from stealing it?" Well, if it is of no value, then no one is going to want to steal it, so why would you spend money on a safe to protect something that no one wants to steal in the first place?
If there is no reason for someone to hide or override your method then no one will. If there is a reason for someone to hide or override your method, then who are you to tell them not to? You are providing a base class; you are the servant of the derived class author, not their master.
Now, sometimes being a good servant means building something that resists misuse, is robust, and reasonably priced. I encourage people to build sealed classes, for example. Designing secure, robust, inheritable classes that meet the real needs of inheritors is expensive and difficult.
But if you are going to create a robust unsealed base class designed for inheritance, why try to stop the derived class author from hiding, if they have a reason to do so? It cannot possibly hurt the base class. The only people it could hurt are the users of the derived class, and those people are the derived class author's problem, not yours.
There is no way to stop member hiding. If you don't make it virtual or abstract, then a derived class cannot override it properly anyway, hiding isn't polymorphic.
If a derived class hides it using the new operator, then they are opening up problems for themselves as any code that decides to use a reference to the base class will not touch the derived member. So basically, all code that utilises the "base class"-ness of the type hierarchy will bypass all member hiding anyway.
The sealed keyword only works if a derived type overrides a base type and doesn't want it to be overridden further... not sure how it plays with the new operator though. Most likely the member hiding will still be allowed, but will still have the same direct-type problem.
Your task is done by not making the method virtual or abstract, if a person wants to hide members then they are responsible for anything that breaks because they decided to abuse the design.
I think you should not worry about this. If you don't write it as virtual then you are making clear that it is not intended to be overridden and in fact you will receive a warning if you will override it (without the "new" modifier):
Warning: [...] hides inherited member [...].
Use the new keyword if hiding was intended
If you have this fear you should worry about any method that you write in a non-sealed class. So the job for you is just make sure that the design of your class is consistent and clear and if someone wants to inherit it then should be not dumb to just go and redefine non-virtual properties/methods. You cannot completely shield yourself from others stupidity :).
As far as I can tell, you apparently can't do that on a property level. However, if you seal the class:
public class Base
{
public int ID { get; set; }
}
public sealed class Child : Base
{
/// blah
}
then ...
public class Grandchild : Child
{
public int ID { get; set; }
}
will throw an error on the class definition, so using new doesn't even come into play.
Not an exact solution to your problem, but it does keep others from extending or interfering with your API.
Does it actually matter if someone does put a 'new' implementation in? I'm assuming you will always be referring to the base class in any code using that property since that is where it is declared and since it's not override or virtual it won't polymorphically call up to a 'new' implementation anyway.
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.
What is the 'correct' way of providing a value in an abstract class from a concrete subclass?
ie, should I do this:
abstract class A {
private string m_Value;
protected A(string value) {
m_Value = value;
}
public string Value {
get { return m_Value; }
}
}
class B : A {
B() : this("string value") {}
}
or this:
abstract class A {
protected A() { }
public abstract string Value { get; }
}
class B : A {
B() {}
public override string Value {
get { return "string value"; }
}
}
or something else?
And should different things be done if the Value property is only used in the abstract class?
I usually prefer the first approach because it requires less code in child classes.
However, I admit that the semantics of the second approach are clearer in a subtle way. Overriding the property says "this property's implementation is part of my identity." Passing a constructor argument has a different connotation: "I'm setting a value in this other thing, which just happens to be my base class." It implies composition (has-a) rather than inheritance (is-a).
And should different things be done if
the Value property is only used in the
abstract class?
In this case, you should definitely use the first (constructor-oriented) approach so you can hide that implementation detail from subclasses.
Likewise if you need to use the value in the constructor; as Marc mentioned this is an actual technical reason to use the first approach. Though it wouldn't matter in this specific scenario, if someone later modifies the property override to use some other member variable in the derived class, you might have a subtle bug on your hands.
It depends; does the base-class need to know about it in the ctor? If so, the override approach may be a bad idea (virtual doesn't work very well inside the ctor). Otherwise, either is OK.
I think the second idiom is better, as it is more manageable (if your base class needs multiple properties defined in a derived class, the constructor can get messy). It is also clearer where the information comes. If you see the Value property you know that it is defined in a subclass. In the first example, you have to track the definition point of the m_Value variable, which could be modified in the base class.
I think it's pretty much the same, choose one way and stick to that for coherence.
Both your solutions are forcing the derived class to provide a value, which is good; a possible alternative, in case a value should not be required:
abstract class A {
public string Value {
get;
protected set;
}
}
My personal preference is your first option (constructor parameter), because I personally think that it's the clearer one, but it's really a matter of taste.
It depends.
I will use the first way if I need to modify Valuein abstract class.
I will use the second way only if I need to inherit many classes from A and somewhere, I need to box the inherited classes to the base abstract class.
If both of the above are not true, I will use the second approach which is more manageable and clean.
If Value is only used in abstract class, I will declare it as a private field instead of a property.
One major advantage of the second case is that it allows a subclass to define behaviour for the Value property that may be more complex than a simple scalar value. For example, you might want to compute the Value based on other fields that the subclass defines. With the first approach, that is an impossibility, but the second approach allows for that.
I prefer the second. It lets you provide a value without adding an actual field to the class if the value is constant or can be calculated at runtime. The less state you have (fewer fields) the more maintainable you'll likely find the code to be.
Lets take an example in C#
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
}
Now, All the public members of Foo is accessible in Bar except the constructor.
I cannot do something like
Bar bb = new Bar(1);
Why the constructors are not inheritable?
UPDATE
I do understand we can chain constructors, but I would like to know why the above construct is not valid. I am sure there should be a valid reason for it.
Constructors are not inheritable because it might cause weird and unintended behavior. More specifically, if you added a new constructor to a base class, all derived classes get an instance of that constructor. That's a bad thing in some cases, because maybe your base class specifies parameters that don't make sense for your derived classes.
A commonly given example for this is that in many languages, the base class for all objects (commonly called "Object") has a constructor with no parameters. If constructors were inherited, this would mean that all objects have a parameterless constructor, and there's no way to say "I want people who make an instance of this class to provide parameters X, Y and Z, otherwise their code shouldn't compile." For many classes, it's important that certain parameters be defined for their proper function, and making constructors non-heritable is part of the way that class authors can guarantee that some parameters are always defined.
Edit to respond to comments: Ramesh points out that if constructors were inherited as he would like them to be, he could always override base class constructors using privately declared constructors in each derived class. That is certainly true, but there it a logistical problem with this strategy. It requires that writers of derived classes have to watch base classes closely and add a private constructor if they want block inheritance of the base class constructor. Not only is this a lot of work for people writing derived classes, this kind of implicit dependency across classes is exactly the sort of thing that can cause weird behavior.
Ramesh - it's not that what you describe would be impossible to add to a language. In general it's not done because that sort of behavior could confuse people and lead to a lot of extra debugging and code writing.
Quintin Robinson provides some very worthwhile responses to this question in the comments that are definitely worth reading.
They are (via chaining), you would have to chain the constructor in your derived object.. IE:
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
public Bar() : base() { }
public Bar(int j) : base(j) { }
}
The constructors in the derived objects will then chain the calls do the constructors in the base objects.
This article provides some more examples if you want further reading.
One reason why you might introduce a constructor into a class is because it makes no sense to have an instance of that class without a specific "dependency". For example, it might be a data-access class that has to have a connection to a database:
public class FooRepository
{
public FooRepository(IDbConnection connection) { ... }
}
If all the public constructors from base classes were available, then a user of your repository class would be able to use System.Object's default constructor to create an invalid instance of your class:
var badRepository = new FooRepository();
Hiding inherited constructors by default means that you can enforce dependencies without worrying about users creating "invalid" instances.
Suppose constructors were inheritable. How would you disable the inherited constructors in the many cases were they don't make sense for a subclass?
Rather than complicating the language with a mechanism to block inheritance, the language designers opted for simply making constructors not inheritable.
The Foo constructor can only know how to initialize a Foo object, so it makes no sense that it should also know how to initialize any potential subclass
public class Bar : Foo
{
public Bar(int i) : base(i) { }
}
The story the constructor tells is: "Hey base class please do whatever work you need to do to be in a good state so that I can go ahead and set up myself properly".
Constructors are not inheritable for design reasons. (Note that this is the same situation in every object-oriented language of which I know.) The simple answer is that in many cases you'd really not want the same constructors as the base class to be available. See this SO thread for some more complete explanations.
Some discussions
Joel's forum
Eric Gunnerson's blog
The basic idea is to provide as much control to the creator as possible. And you can have private bases. How'd you create the object then?
I think you can do the following:
public class Bar : Foo
{
public Bar (int i)
: base (i)
{
}
}
I may be a bit off -- but it's the general idea.
The simple answer is that the language doesn't work that way.
The real question you are asking for though is why it doesn't work that way :-) Well it is an arbitrary choice, and it follows on from C++ and Java (and very possibly many other langauges that influenced C#).
The likely reason is that the compiler will only generate a constructor that takes no arguments and simply calls the parent is that if you want more than what the compiler makes you do it yourself. This is the best choice since odds are you do more than suply calling the parent constructor.
Really, its because the parent constructor wouldn't fully initialize the child object. A constructor is kind of a personal thing in that respect. That's why most languages don't inherit constructors.