+ 1
In C# what's the difference between readonly and inherited protected class variables?
Protected members of a base class being inherited(as protected) can be modified once just like th readonly variables so what's the difference?
6 odpowiedzi
+ 2
You should distinguish the difference between private/protected/public and readonly.
private and protected fields can be changed but only within the class.
You need to write methods to print their value.
The difference between private and protected is that, if a field is private the derived classes won't know about this field. If a field is protected derived classes know and can changed this field.
If a field is readonly
public readonly int ReadOnlyField = 8;
It can be
public readonly
private readonly
or protected readonly.
Depending on its protection level derived class can use the value (public, protected) of this property or do not even know about it (private).
https://code.sololearn.com/cNfIvzFb67W6
Hope this helps.
+ 2
The derived class does not make the protected field public.
It has some methods that can print the field or change the value of the field as long as it is not readonly.
I only have declared field in the base class.
Please try to explain the second question more, I did not understand that.
+ 2
No.
Please supply a code snippet if you can.
I am a c# developper, and I can read some c++ because of my c# knowledge. My c++ knowledge is limited.
I have never seen, the protection level being changed when deriving from a class.
Protected really does not mean readonly. It means changes can only be done within the class it self. This is a difference.
Have you noticed in my code that I can change the protected field.
+ 2
Yh I think I just mixed up C# and C++ Inheritance, also c++ classes have different implementation and there is no readonly.
My mistake and thanks again, your effort is well appreciated.
https://code.sololearn.com/c0I8IyxAtUro/?ref=app
+ 1
sneeze Thanks for the well written answer, I get what you're trying to say but my question is here:
This derived class takes the inherit the protected field then make it public, what if the derived class is declared protected too so the field is inaccessible making it unchangeable would that make a difference? Or am I mixing c++ with c# inheritance mistakenly?
class DerivedClass : BaseClass
0
No I meant when you inherit another class (in c++ as I remember) you get to choose wether the derived class is gonna define the inherited fields and methods(from base) as public, protected or private.
So if I declare a derived class protected(while inheriting a protected field from base class) wouldn't that make it ready only aswell?