internal abstract methods. Why would anyone have them? - c#

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.

Related

Any ideas of how make internal a base class implementation having a child class of that class public in C#?

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{}

Can we create derived public type from private base type in .net?

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; }
}

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?

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.

Does C# have the notion of private and protected inheritance?

Does C# have the notion of private / protected inheritance, and if not, why?
C++
class Foo : private Bar {
public:
...
};
C#
public abstract NServlet class : private System.Web.UI.Page
{
// error "type expected"
}
I am implementing a "servlet like" concept in an .aspx page and I don't want the concrete class to have the ability to see the internals of the System.Web.UI.Page base.
C# allows public inheritance only. C++ allowed all three kinds. Public inheritance implied an "IS-A" type of relationship, and private inheritance implied a "Is-Implemented-In-Terms-Of" kind of relationship. Since layering (or composition) accomplished this in an arguably simpler fashion, private inheritance was only used when absolutely required by protected members or virtual functions required it - according to Scott Meyers in Effective C++, Item 42.
My guess would be that the authors of C# did not feel this additional method of implementing one class in terms of another was necessary.
No it doesn't. What would the benefit be of allowing this type of restriction?
Private and protected inheritance is good for encapsulation (information hiding). Protected* inheritance is supported in C++, although it isn’t in Java. Here’s an example from my project where it would be useful.
There is a base class in as 3rd party framework**. It has dozens of settings plus properties and methods for manipulating them. The base class doesn’t make a lot of checking when individual settings are assigned, but it will generate an exception later if it encounters an unacceptable combination.
I’m making a child class with methods for assigning these settings (e.g. example, assigning carefully crafted settings from a file). It would be nice to deny the rest of the code (outside my child class) the ability to manipulate individual settings and mess them up.
That said, I think in C++ (which, again, supports private and protected inheritance) it's possible to cast the child class up to parent and get access to parent's public members. (See also Chris Karcher's post) Still, protected inheritance improves information hiding. If members of a class B1 need to be truly hidden within other classes C1 and C2, it can be arranged by making a protected variable of a class B1 within C1 and C2. Protected instance of B1 will be available to children of C1 and C2. Of course, this approach by itself doesn't provide polymorphism between C1 and C2. But polymorphism can be added (if desired) by inheriting C1 and C2 from a common interface I1.
*** For brevity will use "protected" instead of "private and protected".
** National Instruments Measurement Studio in my case.
Nick
You can hide inherited APIs from being publicly visible by declaring that same member in your class as private, and using the new keyword. See Hiding through Inheritance from MSDN.
If you want the NServlet class to not know anything about the Page, you should look into using the Adapter pattern. Write a page that will host an instance of the NServlet class. Depending on what exactly you're doing, you could then write a wide array of classes that only know about the base class NServlet without having to pollute your API with asp.net page members.
#bdukes:
Keep in mind that you aren't truly hiding the member. E.g.:
class Base
{
public void F() {}
}
class Derived : Base
{
new private void F() {}
}
Base o = new Derived();
o.F(); // works
But this accomplishes the same as private inheritance in C++, which is what the questioner wanted.
No, public inheritance only.
You probably want a ServletContainer class that gets hooked up with a NServlet implementation. In my book, not allowing private / protected inheritance is not really a big deal and keeps the language less confusing - with LINQ etc. we allready have enough stuff to remember.
I know this is an old question, but I've run into this issue several times while writing C#, and I want to know...why not just use an interface?
When you create your subclass of the 3rd party framework's class, also have it implement a public interface. Then define that interface to include only the methods that you want the client to access. Then, when the client requests an instance of that class, give them an instance of that interface instead.
That seems to be the C#-accepted way of doing these sorts of things.
The first time I did this was when I realized that the C# standard library didn't have a read-only variant of a dictionary. I wanted to provide access to a dictionary, but didn't want to give the client the ability to change items in the dictionary. So I defined a "class DictionaryEx<K,V,IV> : Dictionary<K,V>, IReadOnlyDictionary<K,IV> where V : IV" where K is the key type, V is the real value type, and IV is an interface to the V type that prevents changes. The implementation of DictionaryEx was mostly straightforward; the only difficult part was creating a ReadOnlyEnumerator class, but even that didn't take very long.
The only drawback I can see to this approach is if the client tries to dynamically cast your public interface to the related subclass. To stop this, make your class internal. If your client casts your public interface to the original base class, I think it'd be pretty clear to them that they're taking their life in their own hands. :-)
First solution:
protected internal acts as public in the same assembly and protected on other assemblies.
You would need to change the access modifier of each members of the class which are not to be exposed through inheritance.
It is a bit restrictive though that this solution requires and forces the class to be inherited to be used by another assembly. Thus the choice of being used only by inheritance or not is taken by the unknowing parent... normally the children are more knowing of the architecture...
Not a perfect solution but might be a better alternative to adding an interface to hide methods and still leaving the possibility of using the parent methods to be hidden though the child class because you might not easily be able to force the use of the interface.
Problem:
The protected and private access modifiers cannot be used for methods that are implementing interfaces. That means that the protected internal solution cannot be used for interface implemented methods. This is a big restriction.
Final solution:
I fell back to the interface solution to hide methods.
The problem with it was to be able to force the use of the interface so that members to be hidden are ALWAYS hidden and then definitely avoiding mistakes.
To force using only the interface, just make the constructors protected and add a static method for construction (I named it New). This static New method is in fact a factory function and it returns the interface. So the rest of the code has to use the interface only!
No it doesn't. What would the benefit be of allowing this type of restriction?

Categories