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.
Related
Any ideas of how make internal a base class having a child class of that class public in c#?
In code:
internal class Base { }
public class Child : Base {}
I have a layered architecture and need to expose to other layers (others assemblies) the Child class but not the Base class. I'm using inherit as a way to avoid class composition and all the voile part associated with it.
Any ideas of how to manage this kind of problem?
This cannot be done. You can hide the class by encapsulation, wrapping it and hiding it as implementation.
Base types will always be known.
Instead of making the class internal, you can make all members internal instead. If you do not want Base to be inherited by other assemblies, declare Base's constructor as internal.
This is known C# limitation, however, this is not CLR limitation.
Not the best solution, but it's possible to define new public class which inherits from internal class, using intermediate language.
Also, there might be some languages which already allow you to do this, so there is a chance you don't really need to write IL.
Though, at this point, I don't understand the necessity of Base. Since it's internal, it can't be consumed by others, and polymorpishm is essentially broken. Code reuse with subclassing, but without polymorpishm does not sound good.
Thugh, as I said, imh it is possibe to create a "public" class from "internal class" using IL, after that, yu will be able to consume that "public" class in C# side, eg
public class MyDervClass : MyILPublicClass{}
I know the question sound somewhat stupid, but i have this scenario.
Context
I am creating 2 background tasks (METRO apps, winRT) which have much parts in common.
Now what i want is, a common base class defining common functionality, and 2 task to be derived from base class.
Problem: Background task should be targetted WinMD, and in this mode, it is not possible to create non sealed public class. If i create sealed, i cannot derive from it, and if i create private, i cannot expose the derived types because base is private.
Concern: What are the ways to achieve the desired functionality. (derived public types from private base). One way could be use of Composition (instead of inheritance)
You simply can't. .NET doesn't allow you to make a derived type more accessible than the base type. You'll have to expose the base type.
Note that if you only give it internal constructors, then other code won't be able to instantiate it or create their own derived types... what's the problem with exposing it at that point?
EDIT: Okay, I've just reread the question, and seen this:
it is not possible to create non sealed public class
So:
Could you make all the types involved internal?
Could you make it a public abstract class? (Does WinMD allow that?)
(If you have any other documentation around what's allowed in WinMD, that would be useful.)
If you're allowed to export interfaces, perhaps you could have your base class and derived classes internal, but make them implement public interfaces. Then have public static methods in a public static class to create instances of these internal types and return them via the interface. Again, I don't know if this is allowed - if you have any links to documentation around what's allowed in WinMD, that would be useful for those of us who haven't done any WinRT development.
Yes, you can hide it in the derived class, then expose the base.Property, i.e.,
new public ScrollBar HorizontalScrollBar
{
get { return base.HorizontalScrollBar; }
}
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?
I was doing some code review today and came across an old code written by some developer. It goes something like this
public abstract class BaseControl
{
internal abstract void DoSomething();
}
If you have a derived class within the same assembly, it would work
public class DerivedControl : BaseControl
{
internal override void DoSomething()
{
}
}
But deriving the base class in a different assembly would give compile time error
DerivedControl does not implement inherited abstract member 'BaseControl.DoSomething()
That got me thinking. Why would anyone declare a method as internal abstract ?
The original programmer wanted to make a derived control available to client code. But prevent the client from inheriting and messing with the virtual method. That's not a bad idea, it is usually easy to break a base class by overriding a method and doing something like forgetting to call the base class method.
One obvious case is where the method receives or returns an internal type. For example, the core methods of the WPF Transform classes process some internal interop types, which WPF doesn't expose as part of its public API. Because the signature includes internal types, the method can't be public or protected. And yet clearly it's appropriate (necessary!) for the various Transform classes to work polymorphically. Therefore the base methods in Transform/GeneralTransform have to be internal.
Another, but related reason is to prevent external derivation. After all, the WPF architects could have exposed a "safe" version of the internal interop types in a protected abstract method, so that users could create their own Transform classes. They didn't because they didn't want to have to cope with the ways that people might use that capability, e.g. creating non-affine transforms. Allowing external derivation would have made the job of other classes in WPF hugely more complex, so the architects decided to allow only "approved" derived classes by making an abstract method internal.
My initial reaction was that there is no good reason, if you want to prevent external inheritance then you should mark the class internal. But that means that the class is totally hidden to other assemblies.
I suppose this method prevents external inheritance while retaining visibility.
By defining a method as internal abstract you want to make sure that only the class in the same assembly can have its implementation for your method.
now if you distribute a dll of it this will avoid the client to inherit and mesup the implementation.
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));