I always wonder if it is possible to have a private class? And, what would be the point of having such class?
Thanks for helping.
Yes it is possible to have a private class, but only as an inner class of another class:
public class Outer
{
private class Inner
{}
}
This is usually useful when you want to encapsulate some logic inside of a class (the outer one), but need a more structured/OO design of code to implement it. I have used this pattern in the past when I need a container class to process some information within a method of a class, but the container class has no meaning outside of this logic. Making the container class a private inner class means that its use is localised to the outer class that utilises it.
It is worth noting that with this structure, the inner class has access to the private members of the outer class, but not the other way around.
Having private non-nested classes (Visible only to their namespace and child namespaces only) would allow to clean code boundaries while programming in the same assembly.
Having for example only an interface and a factory visible from other namespaces in the same assembly while still having all the implementation of the interface and utility classes (that no-one have business knowing out of the namespace) there.
It is still possible to do it somewhat with a big partial class replacing a namespace and nested classes inside but it's a very bad hack and unit testing become nearly impossible.
Yes you can - usually they are nested classes inside another type. This means you can aggregate logic into a nested class without exposing the class to anything else. Internal is also useful for nested classes.
Note however that there are some arguments against a design requiring nested classes - I tend to use them when they seem a good fit though.
You can have a private class, inside another class.
You may use a private class to encapsulate logic and implementation. For example you can declare an implementation of an iterator in your implementation of ICollection.
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 am having a bit of a debate about the use of nested classes. The situation is that a class name makes sense to be repeated in two or more places, and while there is moderate similarity between each of the different instances, they are generally different. The nested classes are not often (if at all) needed beyond the scope of their parent class.
So then, rather than just coming up with three different class names, this seems to make more sense to me.
class A {
class B {
}
class M {
class B {
}
}
class Q {
class B {
}
}
The obvious problem with that is not functionality, but rather consistency/repetition. I was wondering if other developers have ever struggled with the same thing, and what some of the opinions were.
The .net Design Guide advises against it:
"Do not use public nested types as a logical grouping construct; use namespaces for this."
"Avoid publicly exposed nested types. The only exception to this is when variables of the nested type need to be declared in rare scenarios such as subclassing or other advanced customization scenarios."
That's also what the base class library does: In the System.Web.UI namespace, you have DataGridItem, DataListItem, ListViewItem, MenuItem, RepeaterItem, etc. All of these could be called Item and nested inside DataGrid, DataList, etc. However, this would violate the two principles outlined above.
It looks okay when your classes are small. Once they get bloated, you really start thinking about moving them in separate files.
More to your point, if you want to use both A.B and M.B in the same code you have to always type A.B and M.B, which can be a pain.
If class B has any similarities between each inner class instance, would it make sense for you to abstract the similarities of B to a base class that exists alongside A, M, and Q? (I think so.) Then your inner classes, while they may have the same name, would be a little cleaner.
With that said, this type of structure can be seen for things like Metadata in an MVC application. In that instance you'd have something like:
[MetadataType(typeof(A.Metadata))]
class A
{
protected class Metadata
{
...
}
}
[MetadataType(typeof(B.Metadata))]
class B
{
protected class Metadata
{
...
}
}
In these case the inner classes each serve the same purpose but their implementations vary with each parent class. Also, with the Metadata definitions here, it makes a lot of sense to keep a class that helps describe its parent as an inner class. If there's any chance you might want to re-use the inner classes elsewhere then I would move them outside of their parents.
I think it's a little atypical to see this in practice otherwise. I'm sure there are good examples, but I bet there are more bad examples of this type of pattern.
I would say it is sometimes ok, but usually not a good design, to use private nested classes. I once refactored an existing very large class in my project to give it private nested classes. The reason why I did this was that some methods took dozens of parameters and this gave them a more logical grouping. In this sense I see nested classes as a good quick fix. It made sense because no one outside that class had any use for any of those fields.
Generally, I would shy away from using nested classes in an initial design - and think twice before considering them in a redesign. In maintenance, if you have the time, it is better to redesign the whole class and split them out into separate classes in separate files that are internal.
I think this strategy is also better for testability than using nested classes is. Due to greater dependencies with the outer class and other classes in the application, my refactored nested classes weren't much easier to unit test than the original large class that passed around many parameters. If you split nested classes so that they are on their own, you can write more discrete unit tests that actually test units rather than, effectively, combining the unit tests for the outer class and the inner class. This will give you more confidence in saying, "Yes, the inner class works at the unit test level" and "Yes, the outer class works at the unit test level" (which also tests how it fits together with the inner class, e.g. in computing formulas).
I understand your sample is sort of contrived. Still, if your class names are similar enough - or identical - you really shouldn't make them nested classes. As a general rule you should shy away from using nested classes at all.
If I'm remembering correctly, the .NET Framework Guidelines recommends against using nested classes as well. Nested Type Usage Guidelines is a little old (back to version 1.1), but the principles still apply.
Do not use nested types if the following are true:
The type must be instantiated by client code. If a type has a
public constructor, it probably should not be nested. The rationale
behind this guideline is that if a nested type can be instantiated, it
indicates that the type has a place in the library on its own. You can
create it, use it, and destroy it without using the outer type.
Therefore, it should not be nested. An inner type should not be widely
reused outside of the outer type without a relationship to the outer
type.
References to the type are commonly declared in client code.
Well you can use namespaces to do things like this too (just create a new folder in VS). Which is better for organising and will pretty much give you the same result.
But if the subclass is only relevant to the parent class then I don't see the harm in it.
Then again, if you are calling them the same thing I would guess they do a similar drop and you may want to look into abstraction, perhaps your parent classes could be done differently too. Really depends on what you need them to do though
I like doing that, for me it makes the use more clearer and especially finding names less of a problem. But usally i try to limit this on private classes or public enums.
For example
class Text {
enum Alignment
class UIElement {
enum Alignment
or
class Quadtree {
private class Node
class Octree {
private class Node
Don't create a nested class if there is any chance (or business reason) that you'll have to use it in some other place (use namespace instead and dot not hesitate to create class with long name if you need to).
For instance I use nested class for DTO between my controller and my view, or in a class to represent a cache entry.
If you want to name them the same but have different types you could use different namespaces.
Namespace1.MyClass{}
Namespace2.MyClass{}
This will end up with two different types despite the classes being named the same.
It really depends on the functionality of the nested class. That is very similar to the way the C++ STL defined iterator differently in each class. There's nothing wrong with the practice, per se, as long as the concept of each is truly different based on the encompassing class.
It can be, somewhat, a matter of style and taste, but personally I don't see an issue as long as they are truly different and dependent on the definition of the encapsulating class. It does tend to get more confusing, though, if they are publicly visible outside the class. Thus, I would not personally expose the classes publicly.
There's nothing inherently wrong about nested classes, as long as you stick to the following rules of thumb:
Never public or internal. There are special cases, such as when you're using a nested class to implement IEnumerator. But even then, the class itself should be kept private, since instances of it are being returned as IEnumerator, and it's really just being done as a way to avoid junking up the namespace with classes that aren't supposed to be instantiated.
Keep them small. A private nested class that's really just used for storing and passing around data in a more organized way is fine, and can sometimes be a very useful tool. (Not entirely unlike how anonymous classes are useful.) But if you're looking to use them to package up large chunks of functionality, it becomes a code smell that suggests you might want to consider refactoring the outer class instead.
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 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));
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.