Multiple inheritance problem in C# - c#

I am in a situation where i need to use multiple inheritance in C# with WPF.
I am making a control lets say Control-1 that is derived from combobox control. I added some dependency properties as well as methods to the my control Control-1 class. Most of the properties and methods(infact the same implementation of properties and methods) in my control-1 can also be used in another control called Control-2 but that control should not be derived from combobox control (as is the case with Control-1).
I want to seperate the common dependency properties and methods in another class but seperating it in another class require me to derive my control class (control-1) from combobox control and the common class containing properties and methods.
Is there a design that can solve my problem.
Note: The question is about C# using the WPF framework's dependency properties, which require static members and not just on C# in general.
Related
How to reuse code when multiple inheritance is not an option?
Multiple Inheritance in C#
How To Implement Shared Behavior Between Classes (Without Multiple Inheritance Of Course) in C#
What are some good alternatives to multiple-inheritance in .NET?

One solution that may work for you is to create an interface instead, and put your implementation in extension methods.

sounds to me like a good time to use the decorator pattern here are some resources:
http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_wrapper302122006080905AM/csharp_wrapper3.aspx
http://andrewtroelsen.blogspot.com/2009/04/decorator-pattern-extension-methods.html

I can't speak directly to the Dependency Property situation, so I'll talk about the general problem, if that's helpful.
You can't do multiple inheritance of implementation in C#. However, you can attach an interface.
So you can define the interface:
interface IWhatever
{
...
}
And then, you can implement the functions of that interface in a class like so:
class M : IWhatever
{
}
And, now, you take the classes that you would like to have this additional functionality on:
class B : MustExtend, IWhatever
{
private M myMImpl = new M();
// implement functions, call to 'myMImpl' for implementation.
}
This is called 'composition'. It can be useful in some circumstances, and is generally underused, I'd think :)

I've used stubs that are called from the derived class and take the class of base type as an argument. This leaves me with several one line functions. Too bad.

The problem with extension methods and interfaces is that dependency properties require the declaration of static members and public properties, for example:
public PermissionEnum Permission
{
get { return (PermissionEnum)GetValue(PermissionProperty); }
set { SetValue(PermissionProperty, value); }
}
public static readonly DependencyProperty PermissionProperty =
DependencyProperty.Register("Permission", typeof(PermissionEnum), typeof(SecurityMenuItem), new FrameworkPropertyMetadata(PermissionEnum.DeliveryView));

Related

Remove dependency on inherited abstract class references

I am trying to setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed.
I have the following setup:
namespace Workgroup.DomainClasses
{
public abstract class WorkGroupOrder
{
private ICollection<WorkGroupItems> _items;
protected WorkGroupOrder()
{
_items = new List<WorkGroupItems>();
}
protected int OrderId { get; set; }
protected virtual ICollection<WeAccount> Items
{
get { return _items; }
set { _items = value; }
}
}
}
I would prefer that users not use the base WorkGroupOrder so would like to set this up so they are required to implement their own version of the class. If all is good with the base class it would simply be an empty class calling the base constructor but otherwise properties and functionality could be added. The idea for this is that the Workgroup domain is much larger than may be necessary for a single project but we'd like to drive all work from this common model.
using Workgroup.DomainClasses;
namespace Project.DomainClasses
{
public class Order : WorkGroupOrder
{
public string OrderComment { get; set; }
}
}
The issue I'm having is that I'm required to reference both domain models to implement. There is an error below in the Testing() method that I must also reference Workgroup.DomainClasses in order to instantiate the class. I'm not that familiar with abstract classes so is this just the nature of the abstract type? I'd prefer to remove this dependency if possible.
using Project.DomainClasses;
namespace Project.DataLayer
{
public class Testing
{
public void Testing()
{
Order o1 = new Order();
}
}
}
A few questions.
Does this organization make sense or is there a better way to
support my desire of providing a common model that could potentially
be extended?
How would I access the properties of both the base
abstract class and the concrete class? In my Testing() method I am unable
to access `o1.OrderId` for example.
I'd like to remove meta-knowledge of the abstract class from the developer. How would it be best to execute the constructor without explicitly requiring the developer to do so?
Ultimately I'd like to require developers to create their own instance of the class to avoid implementing the base model directly. I'd also like to build in the proper visibility to prevent them from going directly to the Workgroup objects.
It seems like there are a few different issues in play here.
Firstly, using a namespace to try to segregate out base functionality is not a viable option because all derived classes will need access to the namespace of the base class by default (in order to inherit). Any developers extending your base classes will need access to the namespace containing the base classes.
Controlling access to functionality or data is generally best accomplished using access modifiers (eg, public, protected, or private) or public properties with public get{ } and protected set{ } or private set{ } (ie, getters and setters with different acccess levels). If you wish to hide implementation details from the end users, then an interface is the right approach to take (like an API, for example).
Secondly, by marking any class abstract you will automatically deny other developers the ability to instantiate that class directly. They will be forced to create a class derived from the abstract class (aka, a "concrete" class) in order to use the abstract base class's methods and properties.
Third, the reason you couldn't access property o1.OrderId in your test code is because that property has an access modifier of protected. This means that only the base class and its derived classes can internally access this property. To expose it to the end user, it must be marked public.
Unfortunately, I do not really understand what you mean with "setup a scenario where we can create a common set of models for our workgroup and then implement or extend them if/when needed". What is a workgroup in your context? And why should (all) other classes derive from it?
Anyway, you cannot use o1.OrderID because this property is protected which means it is only visible within the scope of WorkOrderGroup and subclasses that derive from it. Make this property public and you can access it everywhere.
Furthermore, and please take no offence, but it seams that you somewhat struggle with the object-oriented concepts of encapsulation and inheritance. I would advise you to have a look at these concepts (you can e.g. start here) and get a good understanding what they do and how to use them when implementing functionality. With the current information, I would not advise you to structure your code like you explained in your question.
Finally, some general hints on practices in object-oriented languages:
Favor composition over inheritance: this means that you should extend existing classes by encapsulating them instead of inheriting from them. In most cases this is more flexible.
Take a look at the SOLID princples: they provide really good instructions that you should consider on every class you write.
Take a look at Design Principles and maybe Domain-Driven-Design: there is a lot of guidance on the internet out there with a lot of examples. With every examples you get a better feeling how to approach new problems and how to model them in OOD.
I hope this answer guides you in the correct direction.

Implementing DynamicObject functionality on a class that extends another class

I need an advise on the best way to simulate multiple inheritance for a C# class that needs to be extended with support for dynamics.
I have a class MainClass needs not to be dependent on DLR - all its properties and methods are statically compiled. It has plenty of overloaded operators. It is some sort of DSL.
ExtendedClass is basically a MainClass with support for C# dynamics, e.g. in addition to all MainClass features it needs to overload DynamicObject's TryGetMember/TryInvokeMember, so clients may use it with extended properties evaluated at runtime.
Here comes a problem of DynamicObject being a class, not an interface. So ExtendedClass must only derive from DynamicObject which means it should basically duplicate all MainClass functionality.
I guess believe this is not uncommon situation (two similar classes, one must derive from some system class, thus making it impossible to reuse functionality by inheriting one from another). Is there any smarter way of dealing with this situation than straightforward approach: add MainClass as a member field to ExtendedClass, duplicate all its methods/properties and simple forward it to the contained instance of MainClass?
It's hard to say with such a very generic description. The common pattern I'm familiar with is:
public class MainClass{
foo bar();
more stuff {get;set;}
....
}
public class ExtendedClass:MainClass{
protected class Helper:DynamicObject{ ...}
private Helper _helper;
public Extended(){
_helper= new Helper(this);
}
public dynamic Extend {
get{ return _helper};
}
}
That way your dynamic properties or methods have their own namespace if you will by requiring to call Extend first to sort of trampoline.

Why can't my public class extend an internal class?

I really don't get it.
If the base class is abstract and only intended to be used to provide common functionality to public subclasses defined in the assembly, why shouldn't it be declared internal?
I don't want the abstract class to be visible to code outside the assembly. I don't want external code to know about it.
UPDATE: This question was the subject of my blog on November 13th of 2012. See it for some more thoughts on this issue. Thanks for the great question!
You're right; it doesn't have to be that way. Other OO languages allow "private inheritance", whereby the fact that D inherits from B can only be taken advantage of by code that has the ability to see B.
This was a design decision of the original C# designers. Unfortunately I am away from my desk right now - I'm taking a couple of days off for the long weekend - so I don't have the language design notes from 1999 in front of me. If I think of it when I get back I'll browse them and see if there is a justification for this decision.
My personal opinion is that inheritance should be used to represent "is a kind of" relationships; that is, inheritance should represent the semantics of the domain being modelled in the language. I try to avoid situations where inheritance is used as a code sharing mechanism. As others have mentioned, it's probably best to prefer composition to inheritance if what you want to represent is "this class shares implementation mechanisms with other classes".
By inheriting from a class, you expose the functionality of the base class through your child.
Since the child class has higher visibility than its parent, you would be exposing members that would otherwise be protected.
You can't violate the protection level of the parent class by implementing a child with higher visibility.
If the base class is really meant to be used by public child classes, then you need to make the parent public as well.
The other option is to keep your "parent" internal, make it non-abstract, and use it to compose your child classes, and use an Interface to force classes to implement the functionality:
public interface ISomething
{
void HelloWorld();
}
internal class OldParent : ISomething
{
public void HelloWorld(){ Console.WriteLine("Hello World!"); }
}
public class OldChild : ISomething
{
OldParent _oldParent = new OldParent();
public void HelloWorld() { _oldParent.HelloWorld(); }
}
I think the closest thing you can do is prevent other assemblies creating the abstract class by making its constructor internal, to quote from MSDN:
An internal constructor prevents the abstract class from being used as the base class of types that are not in the same assembly as the abstract class.
You can then try adding an EditorBrowsableAttribute to the class to try and hide it from IntelliSense (though, I've had mixed results using it to be honest) or put the base class in a nested namespace, such as MyLibrary.Internals to seperate it from the rest of your classes.
I think you're mixing concerns here, and C# is to blame, actually (and Java before it).
Inheritance should serve as a categorization mechanism, whereas it's often used for code reuse.
For code reuse it's always been known that composition beats inheritance. The problem with C# is that it gives us such an easy way to inherit:
class MyClass : MyReusedClass { }
But in order to compose, we need to do it by ourselves:
class MyClass {
MyReusedClass _reused;
// need to expose all the methods from MyReusedClass and delegate to _reused
}
What's missing is a construct like a trait (pdf), which will bring composition to the same usability level as inheritance.
There's research about traits in C# (pdf), and it would look something like this:
class MyClass {
uses { MyTrait; }
}
Although I'd like to see another model (that of Perl 6 roles).
UPDATE:
As a side note, the Oxygene language has a feature that lets you delegate all members of an interface to a member property that implements that interface:
type
MyClass = class(IReusable)
private
property Reused : IReusable := new MyReusedClass(); readonly;
implements public IReusable;
end;
Here, all interface members of IReusable will be exposed through MyClass and they'll all delegate to the Reused property. There are some problems with this approach, though.
ANOTHER UPDATE:
I've begun implementing this automatic composition concept in C#: take a look at NRoles.
I think this would violate the Liskov Substitution Principle.
In cases like this, I have used internal classes and prefer composition over inheritance. Is there anything about your design that prohibits containing all such functionality in your internal class, and then have your public classes contain an instance of this internal class?

How to handle a class you want to extend which is sealed in the .NET library?

I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library.
This is often a common and useful task to do, so it got me thinking, in this case, what solutions are there? I believe there was a "method" demonstrated to extend a sealed class in the article I read, but I cannot remember now (it wasn't extension methods).
Is there any other way?
Thanks
There is 'fake' inheritance. That is, you implement the base class and any interfaces the other class implements:
// Given
sealed class SealedClass : BaseClass, IDoSomething { }
// Create
class MyNewClass : BaseClass, IDoSomething { }
You then have a private member, I usually call it _backing, thus:
class MyNewClass : BaseClass, IDoSomething
{
SealedClass _backing = new SealedClass();
}
This obviously won't work for methods with signatures such as:
void NoRefactoringPlease(SealedClass parameter) { }
If the class you want to extend inherits from ContextBoundObject at some point, take a look at this article. The first half is COM, the second .Net. It explains how you can proxy methods.
Other than that, I can't think of anything.
Extension methods is one way, the alternative being the Adapter Pattern. Whereby you write a class that delegates some calls to the sealed one you want to extend, and adds others. It also means that you can adapt the interface completely into something that your app would find more appropriate.
this method may have already been mentioned above by it's formal name, but i don't know it's formal name, so here it is. This example "extends" the TextBox class (example in VB). I believe an advantage of this method is that you do not need to explicitly code or expose built-in members. Hope this is relevant:
VB Class Module "MyTextBox":
public Base as TextBox, CustomProperty as Integer
Private Sub Init(newTextBox as TextBox)
Set Base = newTextBox
End Sub
public Property Get CustomProperty2() As String
CustomProperty2 = "Something special"
End Property
To call the code, you might say:
Dim MyBox as New MyTextBox
MyBox.Init MyForm.TextBox3
from here you have access to all built-in members, plus your custom members.
Debug.Print MyBox.Base.Text
MyBox.CustomProperty = 44
For extra polish, you can make Base the default property of the class, and then you can leave out "Base" when you call properties of the Base class. You call Base members like this:
Debug.Print MyBox().Text
MyBox().Text = "Hello World"
VBA Demo
Maybe use the Decorator pattern?
Other than extension methods, this is the only sensible technique I can think of.
No, you can't extend a sealed class in any legitimate way.
TypeMock allows you to mock sealed classes, but I doubt that they'd encourage you to use the same technique for production code.
If a type has been sealed, that means the class designer has not designed it for inheritance. Using it for inheritance at that point may well cause you lots of pain, either now or when the implementation is changed at a later date.
Prefer composition to inheritance - it's a lot more robust, in my experience. See item 16 in "Effective Java (2nd edition)" for more on this.
The only way I know to "extend" a sealed class without extension methods is by wrapping it. For example:
class SuperString
{
private String _innerString;
public SuperString(String innerString)
{
_innerString = innerString;
}
public int ToInt()
{
return int.Parse(_innerString);
}
}
You'd need to expose all of the same methods/properties as the string class.
Some frameworks allow you to extend existing objects. In WPF, see Dependency Properties. For Windows Forms, see IExtenderProvider.
How about extension methods? You can "add" additional methods that way, without having to deal with the inheritance restriction.

internal constructor

Yesterday I thought it would be nice to implement my own Trigger in a WPF app. I created a class MyTrigger which inherited TriggerBase. TriggerBase is a public abstract class. So inheritance isn't a problem. But the constructors inside this class are marked internal. The compiler throws an error because the is no valid constructor. Why does anyone create a public class but marks the constructors as internal?
If you want the class to be visible, but only allow it to be subclassed within your own assembly. The subclasses may have public constuctors themselves - or they may be accessed with a factory.
I can't comment on whether that's a good design decision for TriggerBase in WPF, but it's at least reasonable in some situations.
One reason that I could think of is that the actual creation of new instances would be handled by another public class in the same assembly. This would force that you create the instance through this other class - possibly some sort of a factory pattern implementation.
It's public because it's used as a base class for the triggers that ship with WPF (Trigger, MultiTrigger, EventTrigger, DataTrigger etc). It it wasn't public then you wouldn't be able to flag these classes as public.
The constructors are internal because they don't intend for you to use it yourself. I'd guess you're suppose to derive from one of the classes mentioned above.

Categories