Can anyone explain, why we can do such thing and why we need this
public class OuterClass
{
public class InnerClass
{
}
}
Why we need public inner whatever: struct, class, enum or static class?
I think that if it is inner then it must be only private or protected.
You don't generally need public nested types - but they can be useful sometimes. They make it very clear that one type is explicitly associated with another.
They also allow the nested type to access the private members of the enclosing type (in C#), which may be useful at times. I would guess that List<T>.Enumerator may do that, for example. In Java the access rules work the other way round - the enclosing class has access to the private members of the nested classes.
I think would have to explain why you'd want to explicitly prohibit this rather than why it's needed, as such. I can't think of anywhere else that you can specify an access modifier but can't make it public, other than for inconsistency (declaring a public method with an internal return type, for example).
Public inner types are generally not recommended, see this reference
http://msdn.microsoft.com/en-us/library/tdz1bea9(v=VS.71).aspx
...but since there are (may be) exceptions, this is still allowed
Consider this example:
public class TrainingFile {
public List<TrainingFileEntry> getEntries() {
return ...
}
public class TrainingFileEntry {
int x;
int y;
}
}
You want to hide the details of the TrainingFileEntry, but your customer needs to be able to use it. Ofc you could create an own file for this nested class, but such a nested helper class ist mostly not a "standalone" and stuck to the class where it is nested. -)
Its very useful when every member of InnerClass really does belong to one, and only one member of outer class. I have used that construct where OuterClass was a collection of mathematical objects and InnerClass was the actual objects themselves.
Related
stupid question really, I have private variables, which I encapsulated and now I want to access them from another class.
I also have a list in one class and want a lot of classes to access that list (list of objects called fields) (creating a simple farm simulator).
So how can I access them from another class?
I know I can make an instace of a class, but with lists, will that mean that my list won't be the same when I create instances of the class in the classes that I want to access the list in?
I don't think I can use Namespace.class.Something since their not static, or can I?
Maybe use inheritance for list or is that not going to work?
Please help, realllyyy would appreciate any help!!
*thank you in advance
You cannot access a private member from within another class (except the member is a member of a nested class). So the proposal from Konrad Kokosa to use Properties instead was absolutely fine as they should be used to control access from outside the actual class. Having said this you may either turn the access-modifier for that property to public or derive from that class (however, you have to use protected access for the property then).
MyClass {
public static List<Field> MyList {get;set;}
}
AnotherClass {
AnotherClass() {
MyClass.MyList = // whatever
// or also possible
MyClass.MyList.Add(/*new Item*/);
}
}
Private members cannot be used outside of the class (unless you use reflection, which I would not recommend). If you want the members to be available to outside classes, you have to make them "public". If you want your members to be available to all derived classes only, use "protected".
If you want to access the same list from all o the other classes, you should declare it as static:
private static List<Field> s_fields = new List<Field>();
public static List<Field> Fields { get { return s_fields; } }
class A
{
private int aa = 1;
}
class B : A
{
private int bb = 5;
void DoStuff()
{
aa = bb; //Error, as it should
}
}
Versus:
class A
{
private int aa = 1;
class B : A
{
private int bb = 5;
void DoStuff()
{
aa = bb; //Not an error, bummer
}
}
}
Same stuff, just organized differently. I'm using the second method of organizing my classes because it looks so much cleaner to inherit inside of the class for what I'm doing. My problem is that, in the example above, I don't want A's private members to be accessable to B even though it is inside A. I'm beginning to understand that's the point of doing that systematically, but am I really forced to keep them separate if I want A's private members to be private from B?
Yes, you're really forced to keep the declarations separate if you don't want B to access A's private members because nested classes have access to their containing classes private members.
You can't do that.
A nested class is a class member, just like a method. All class members can see other members, even private. Just as you can see private fields from a method.
If you want to do that, it probably means your nested class shouldn't be nested in the first place.
am I really forced to keep them separate if I want A's private members to be private from B?
Yes. from the documentation
A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members.
Also why does it matter? Since you control what goes in B, if you don't want B to use anything from A then don't use it.
All of the other answers here are correct in mentioning that you cannot accomplish what you are trying to do, if you nest your classes rather than use separate declarations and inheritance.
One thing you should examine is the true design behind what you're doing and let that guide what design method you choose.
If you don't intend for any outside class to access Class B and its functionality is strictly required within Class A, then there is no way to (and no real need to) hide the members of A from B because B in this case is actually a member of A, with the same access privileges as say a method within that class.
If you plan to expose this class to other potential classes, then it's matter of design (not a matter of code cleanliness/organization) that should draw you to the first method and keep the declarations separate.
I am trying to study about nested class in c#. After reading many documents and goggling, I still not yet clear about when to use nested classes. But as far as I understand I did a small sample program. I am pasting my code below. Is this nested class program implemented in correct logic? . What actually a nested class using for ?. and also I have a doubt arise in this program and I specified that doubt in the program. Please help me ...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Bank bankObj = new Bank();
bankObj.CreateAccount();
bankObj.ShowMyAccountNumber();
}
}
class Bank
{
static int accountNumber; // here if I just declare this as int accountNumber without static it showing an error in the CreatePersonalAccount(int accNo) method's first line ie accountNumber = accNo; as "Cannot access a non-static member of outer type." What actually this error mean ?
public class BankAccountSection
{
public bool CreatePersonalAccount(int accNo)
{
accountNumber = accNo;
return true;
}
}
public void CreateAccount()
{
bool result = new BankAccountSection().CreatePersonalAccount(10001);
}
public void ShowMyAccountNumber()
{
MessageBox.Show(accountNumber.ToString());
}
}
Nested classes are usually used for small utility classes that have no use outside the enclosing (outer) class. For that reason, nested classes are usually private. (There's even an FxCop rule for that.)
Your code
In your case, the nested class BankAccountSection is not really useful, since it has no state by itself. CreatePersonalAccount might as well just be a method of the outer class.
Regarding static int accountNumber;: This will make accountNumber a shared field across all Bank objects, which defeats the whole purpose. Don't do that. If you really need to set a field of the Bank object inside the inner class, you need to pass a reference of the Bank object to the inner class. (This is different to Java, where such a reference is available automatically under some circumstances.) In your particular case, just get rid of the inner class.
Examples for legitimate use cases
You have a large algorithm inside a method. You realize that extracting this algorithm into its own class using many small methods and instance variables would increase readability. Since the algorithm is very specific and probably not useful for other classes, you put the algorithm into an inner class. Thus, you avoid cluttering your outer class with instance variables only used by that algorithm.
You create a List data structure, which is internally implemented as a linked list. Since you don't expose the list nodes to the outside world, you make the nodes an inner class.
Related:
Why/when should you use nested classes in .net? Or shouldn't you?
You seem to think that nested classes in C# behave how they do in Java. That in other words, unless a nested class is declared as static, that it will share the instance of the enclosing class. In C# this is not the case. There is no such thing as that sort of thing in C# -- all nested classes are implicitly static.
This is why you cannot access accountNumber from the nested class unless that field is declared static. (Since the nested class has no access to any particular instance) The idomatic solution to this problem in C# is to pass the instance of the enclosing class into the nested class (presumably by passing this via a constructor argument when instantiating it).
First, that's not a nested class, they are just two classes in one file.
Now, even if it were a nested class, this would probably be an example of when NOT to use nested classes. You should definitely separate your logic from your GUI logic.
I'm don't really think you should be using nested classes anyway, they are in my opinion hard to mantain, but I might be wrong. If I really needed to use nested classes I'd probably do so only when the child class is tightly related.
The error is because you can not access a member of a non static class without its object.
if you do so then it must be declared static.
I have a class with a public property, that I want to restrict access to _for_some_modules_.
(The modules that use this class reside in different assemblies, so internal does not help.)
My first thought was to subclass, and make the derived property accessor private or protected, but this is not possible. The derived property has to have the same access rights. (See http://msdn.microsoft.com/en-us/library/75e8y5dd.aspx)
Any suggestions? I assume it is a common task to make a more restricted variant of a class?
Thanks!
You can use the InternalsVisibleToAttribute to make the internal members of the class visible to other assemblies (as many as you like). The documentation page has an example.
I assume it is a common task to make a
more restricted variant of a class?
This is not a common task since it violates the Liskov substitution principle - you can't use the sub class the same way as you would use the base class in regards to the property you restrict access to. You should consider refactoring your class hierarchy.
You could solve the problem through composition - make the class A internal only and write a public wrapper class that has a member of type A and delegates and controls access to the A's properties / methods.
Making more restricted subclasses is actually not common because it would break consumers of the base class that assumed they had access to the public members. In general, your classes should start out restrictive and get less so as they specialize, not vice-versa.
The concept you're looking for is called a "friend" class in other languages, but C# (purposely) doesn't implement them. The InternalsVisibleToAttribte is as close as it gets, but that is applied at the assembly level, so it may not work for you.
Without more information on why you are trying to restrict access this way, it's hard to give any good general-purpose alternatives. The access modifiers like public/private/etc aren't designed to be a security mechanism, since Reflection will get you access to read/write everything regardless. They're more of a hint to the consumers as to what is safe to use -- public members will usually remain stable across new versions, while private (implementation-detail) members are more likely to change.
You can always do something like this:
class MyBaseClass
{
protected string MyRestrictedProperty { get; set; }
}
class MyClass : MyBaseClass
{
public string MyPublicProperty
{
get { return MyRestrictedProperty; }
set { MyRestrictedProperty = value; }
}
}
I want to do the following
public abstract class MyAbstractClass
{
public static abstract int MagicId
{
get;
}
public static void DoSomeMagic()
{
// Need to get the MagicId value defined in the concrete implementation
}
}
public class MyConcreteClass : MyAbstractClass
{
public static override int MagicId
{
get { return 123; }
}
}
However I can't because you can't have static abstract members.
I understand why I can't do this - any recommendations for a design that will achieve much the same result?
(For clarity - I am trying to provide a library with an abstract base class but the concrete versions MUST implement a few properties/methods themselves and yes, there are good reasons for keeping it static.)
You fundamentally can't make DoSomeMagic() work with the current design. A call to MyConcreteClass.DoSomeMagic in source code will be translated into MyAbstractClasss.DoSomeMagic in the IL. The fact that it was originally called using MyConcreteClass is lost.
You might consider having a parallel class hierarchy which has the same methods but virtual - then associate each instance of the original class with an instance of the class containing the previously-static members... and there should probably only be one instance of each of those.
Would the Singleton pattern work perhaps? A link to the MSDN article describing how to implement a singleton in C#:
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In your particular example, the Singelton instance could extend an abstract base class with your MagicId in it.
Just a thought :)
I would question that there are "good reasons" for making the abstract members static.
If your thinking is that these members might reflect some property of the derived class itself rather than a given instance, this does not necessarily mean the members should be static.
Consider the IList.IsFixedSize property. This is really a property of the kind of IList, not any particular instance (i.e., any T[] is going to be fixed size; it will not vary from one T[] to another). But still it should be an instance member. Why? Because since multiple types may implement IList, it will vary from one IList to another.
Consider some code that takes any MyAbstractClass (from your example). If this code is designed properly, in most cases, it should not care which derived class it is actually dealing with. What matters is whatever MyAbstractClass exposes. If you make some abstract members static, basically the only way to access them would be like this:
int magicId;
if (concreteObject is MyConcreteClass) {
magicId = MyConcreteClass.MagicId;
} else if (concreteObject is MyOtherConcreteClass) {
magicId = MyOtherConcreteClass.MagicId;
}
Why such a mess? This is much better, right?
int magicId = concreteObject.MagicId;
But perhaps you have other good reasons that haven't occurred to me.
Your best option is to use an interface with MagicId only using a setter
public interface IMagic
{
int MagicId { get; }
}
By the nature of Static meaning there can only be one (yes like Highlander) you can't override them.
Using an interface assumes your client will implement the contract. If they want to have an instance for each or return the value of a Static variable it is up to them.
The good reason for keeping things static would also mean you do NOT need to have it overridden in the child class.
Not a huge fan of this option but...
You could declare the property static, not abstract, virtual and throw a NotImplementedException which returns an error message that the method has to be overridden in a derived class.
You move the error from compile time to run time though which is kinda ugly.
Languages that implement inheritance of static members do it through metaclasses (that is, classes are also objects, and these objects have a metaclass, and static inheritance exists through it). You can vaguely transpose that to the factory pattern: one class has the magic member and can create objects of the second class.
That, or use reflection. But you can't ensure at compile-time that a derived class implements statically a certain property.
Why not just make it a non-static member?
Sounds like a Monostate, perhaps? http://c2.com/cgi/wiki?MonostatePattern
The provider pattern, used by the ASP.NET membership provider, for example, might be what you're looking for.
You cannot have polymorphic behavior on static members, so you'll have a static class whose members delegate to an interface (or abstract class) field that will encapsulate the polymorphic behaviors.