C#: Extending from more than 1 class
Asked Answered
E

2

6

Suppose I have a ViewModel TabViewModel that Extends ObservableObject the class for ViewModels in the MVVM Foundation Framework. Then I also have a EditorTabViewModel that extends TabViewModel, Now I need to extend DependencyObject to implement DependencyProperties. I cannot extend more than 1 class. How might I implement this? I could have an "intermediate" class like ...

TabViewModel : ObservableObject

EditorTabViewModel : TabViewModel

DependentEditorTabViewModel : DependencyObject

but thats 1 extra unnecessary class. Any better way to do this?

UPDATE

Ops actually I cant do the above. DependentEditorTabViewModel still need to extend EditorTabViewModel ... apart from DependencyObject

Ensign answered 17/10, 2010 at 2:12 Comment(0)
B
2

C# does not support Multiple Inheritance. Your best bet is to use Interfaces, rather than parent classes.

Even if you don't have the option of using interfaces (maybe you don't have access to the code), it's generally better to prefer composition over inheritance. Do you really need to inherit both of these classes, or can you compose with them instead?

Broom answered 17/10, 2010 at 3:16 Comment(2)
In my above scenario, how could I implement composition over inheritance? I read about that b4 but in this case, maybe my mind is not working well :)Ensign
@jiewmeng: I'm afraid I don't know anything about the MVVM Foundation Framework, so I can't help with the details. Sorry.Broom
U
1

Its not an extra class if you're accomplishing what you need. Here is how you would go about that:

DependentEditorTabViewModel : DependencyObject

TabViewModel : DependentEditorTabViewModel
Unorganized answered 17/10, 2010 at 3:2 Comment(2)
I think I made a similar mistake ... apart from DependencyObject, I still need to extend ObservableObject. In other words, I need the resultant class to extend mainly DependencyObject, ObservableObject.Ensign
Ok. Unfortunately, c# doesn't support multiple inheritance. Look into implementing an interface instead.Unorganized

© 2022 - 2024 — McMap. All rights reserved.