If we inherit a class do the private variables also get inherited?
I know that "Yes, the variables are inherited but cannot be accessed directly by the class interface."
What I want to know is how can we access the private variables/methods from the child class
What I am trying to say is that private members are also inherited.But how to access the same without making them protected.
I know that "Yes, the variables are inherited but cannot be accessed directly by the class interface."
So you know the answer then.
What I want to know is how can we access the private variables/methods from the child class
You can’t, that’s why they are private (rather than, say, protected). The whole intention of making them private is so that you cannot access them from anywhere, notably including child classes.
Explicitly breaking this encapsulation is almost always a sign of a broken design and shouldn’t ever be part of a normal code flow. However, there are situations in which you want to reason about some code, and in these situations it may be necessary to examine even private values. Reflection libraries allow this. Here’s a simple example using the System.Reflection capabilities:
class Widget {
private readonly string identifier;
public Widget(string identifier) {
this.identifier = identifier;
}
}
class MainClass {
public static void Main(string[] args) {
var widget = new Widget("my_test_widget");
var type = widget.GetType();
var field = type.GetField("identifier",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
Console.WriteLine($"{field} = {field.GetValue(widget)}");
}
}
Make them protected. For variables, make a protected property that the child classes then use.
You can only access private variables/methods from a derived class using reflection. You cannot access them in a "natural" way, since the whole point of making them private is to hide them from other classes (including derived classes).
Make it protected property instead of private member.
What I want to know is how can we access the private variables/methods from the child class
.........
But how to access the same without making them protected.
You might want to try using reflection:
Here is a similar question / answer that explains how this can be done.
Related
This question already has answers here:
In C#, what is the difference between public, private, protected, and having no access modifier?
(19 answers)
Closed 3 years ago.
what is the difference between 'protected' and 'private protected' access modifiers in C#?
Can someone please explain with examples?
Thanks in advance.
It's about the acces modifier. More specific: inheritance and multiple assemblies. Consider the following:
For normal protected (explained with along private):
class Base
{
private bool X;
protected bool Y;
}
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base`
}
}
class B
{
public void Foo()
{
A a = new A();
a.X = false; //error: cannot access private member.
a.Y = false; //error: cannot access protected member.
}
}
Now the difference with private protected is that it must live in the same assembly to be accessible:
So:
class A : Base
{
public void Foo()
{
X = false; //error: cannot access private member.
Y = true; //can access protected member, but only from classes with `: Base` AND
//they need to be defined in the same assembly as Base
}
}
Is valid, but only if both A and Base are compiled in the same assembly/dll/exe etc.
Now, since that clear, when would you use an actual private protected?
A lot can be said about this. Some (including me) would argue that the use of private protected is an anti-pattern, because in my oppinion it's closly related to the friend keyword. And I must say, although in contradiction to friend, private protected keeps "the dirt" isolated, it still is arbitrary behavior, logic, depending on the location of it's definition.
Having said that the question remains, when to use it. You might be surprised I punctually used it once, and it was quite helpful.
Consider the following case:
Having a conceptual, decorator pattern styled code base, for example some graphical object system.
All the objects will be "renderable", in various ways.
Because you have a lot, it comes in handy to create a base class which only you are using for convinience.
You don't want to let other user be using this functionality, since it's not well documented and really specifi to your implementation
The classes themselves are public.
.... then I would use private protected ;-)
Private protected is meant to allow the usage of protected member variables of a base class inside derived classes (children) within the same assembly only (same dot net dll).
This means that if you create a class inside an assembly A and you derive that class from another class defined in another assembly B, then your class from assembly A cannot have access to private protected member variables of class from assembly B.
However, using just protected modifier allow using protected member variables across different assemblies when deriving classes.
You can also take a look at the internal modifier which is a similar mechanism of protecting public variables across assemblies.
I'm working with a closed-source base class. Can I somehow change a private field in the base class from my inheriting class?
Assuming the following class structure:
public class Parent
{
private bool age;
}
public class Baby : Parent
{
public bool newAge{
get {
return age;
}
}
}
This currently gives you a compile-time error:
'Parent.age' is inaccessible due to its protection level.
How do you access the field "age" from the Baby class? Can you use reflection or something similar?
You could, using reflection. It looks like this:
public class Baby : Parent
{
private readonly FieldInfo _ageField = typeof(Parent).GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
public int newAge
{
get
{
return (int)_ageField.GetValue(this);
}
set
{
_ageField.SetValue(this, value);
}
}
}
If it's provided by a 3rd party, there is nothing stopping them from changing it, renaming it, it removing it all together. That's one of the points of private. Keep in mind that it might be private for a reason. Tinkering where you aren't suppose to can lead to unexpected results.
You can try to use reflection to get access to private fields and modify them. Like:
typeof(Parent)
.GetField("age", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(parent, 14);
where parent is an instance of Parent.
You can modify those values via reflection. That being said, you probably shouldn't.
Private fields, properties, and methods are all things that are not explicitly guaranteed by the contract of the class. If this 3rd-party API is reliable the public contracts they provide will not change (but they can easily grow).
The private and internal parts are not guaranteed to be the same from release to release. By coupling your code to those parts of the code, you've introduced a lot of risk to your future releases. If you're ok with that risk (and it's well-documented as to why you're doing it), the by all means, reflect away.
If you do go that route, I would recommend an Adapter class that all your consuming code uses instead of this 3rd-party API. With the Adapter pattern, only the one class will need to change in response to the 3rd-part API changes.
Well, since you cannot change the source code of the parent class, there's possibly 2 choices:
If the parent class is a partial class, you can define your own contribution (another Parent class) defining a public Property (it can access private fields).
You can indeed use reflection.
No you cannot do it. Unless you use reflection for example:
Reflection.FieldInfo fields[] =
myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
So i was browsing some code and i came across:
public class Person
{
private string message;
public override string ToString()
{
return message;
}
public static Person CreateEmployee()
{
return new Employee();
}
class Employee : Person
{
public Employee()
{
this.message = "I inherit private members!";
}
}
}
Can someone please explain how the private variable "message" is being used/accessed even though its private??
Private members are accessible to all code within the class, including nested classes.
If you move the Employee class outside the Person class, it will fail until you make the field protected.
The simple fact is, this works because compilers allow it to - the designers thought it was a good thing. Once code is compiled, private/public variables are stored in memory in exactly the same way. (The CLR is simply aware of different metadata attributes for them.)
The justification is: nested classes and their members are still considered to lie conceptually/hierarchically within the parent class. Hence, private members of the parent class are always accessible by these semantics. Besides, it just makes life easy for programmers in many cases without breaking the object-oriented encapsulation rule!
In fact, if you want to think about this in terms of code, any code that falls within the open and close braces of a given class can access its private members, regardless of whether it immediately lies within a nested class/struct/etc.
Because Employee is an inner class of Person.
See this question: can-inner-classes-access-private-variables
Person={private message, private Employee}
Private Employee and private message are siblings, Employee can use the message. If you allocate Private Message into another class and mark it as protected/private outside the Person class, then Employee will not be able to see or use it anymore even with an instance of that class.
I have a class:
public class MyClass {
private List<string> folderList;
// .... a lot of useful public methods here.....
}
Everything is fine. The list of folders is encapsulated, the class is accessible through public methods. OK. Now I need an "options" form that allows a user to choose folders for MyClass. There is a catch: new Setup class must have access to private folderList field (or I have to provide public methods to get and set the folder list - it's essentially the same). In old good C++ I would use 'friend' feature because nobody but Setup class may access folderList. But there is no 'friend' feature in C# (I'm a newbie in the C# world).
P.S. Actually I just made folderList public, but I feel there is a better solution.
Thanks.
You can use "internal" keyword to make your method available only within your assembly/project and if you want to access your internal methods in other project or assembly then you can use "InternalsVisibleTo" attribute, where you can access your internals only in that assembly for which you define this attribute.
MSDN Internal Keyword
I believe the keyword you're looking for is internal. It is loosely equivilent to C++'s friend.
Internal provides assembly-level visibility.
Paired with Femaref's suggestion of using a Property, and you should have your full solution.
I am not sure if this is what he/she wanted. He/she did not put the requirement that the potential client will be in current assembly... Accordingly, when using friend in c++ (which was never considered a good style) you must know the exact type of the class which will be entitled to access the member. If this class is not part of the program you are writing, you cannot grant access this way.
If you want conditional access to some property or method of an instance of a class, you will need to implement some kind of entitlement mechanism, for example:
public IList<Folder> GetFolderList(Object pClient, IEntitlementService pService) {
if (pService.IsEntitledToAccess(this, pClient) {
return folderList;
} else {
throw new AccessNotGrantedException("...");
}
}
I believe there are built-in utilities in the .Net framwork for that purpose, just go and google (or bing)...
As an exact answer to the question I would suggest the following - create a separate interface IFolderList:
interface IFolderList
{
IList<string> FolderList { get; }
...
}
Well, you can add other required members to interface
In the class MyClass implement this interface explicitly.
As a result, the class Setup can gain access to data through an explicit cast to an interface IFolderList or work only with these interface.
An alternative to making an internal method to be used by your Setup class would be to use the Visitor pattern and add a method that takes a Setup class instance as a parameter, then uses the private folderList to initialize/change Setup state as required. Of course that would require the appropriate public methods on the Setup class, so might not fit your needs.
Making folderList field public is the worst case. Exposing implementation details through public fields or through poorly designed public property (there are no differences for collections between public fields and public property with getter and setter).
With public fields you can't promote a field to be a property when you want to add validation, change notification, put it into an interface or change your collection type from one type to another.
BTW, Jeffrey Richter in annotation to Framework Design Guideline mentioned that "Personally, I always make my fields private. I don't even expose fields as internal, because doing so would give me no protection from code in my own assembly"
I think the best way to add explicit interface that expose strict abstraction to MyClass clients.
For example, you may add two separate methods to retrieving folders and to adding new folder to this storage:
class MyClass {
//You should return IList<string>
public IList<string> MyList {get {return myList;} }
//Or even IEnumerable<string>, because you should return
//as minimal interface as your clients needs
public IEnumerable<string> MyList {get {return myList;} }
//You may expose this functionality through internal
//method, or through protected internal method,
//but you should avoid direct access to your implementation
//even for descendants or another classes in your assembly
public void AddElement(string s) {myList.Add(s);}
private List<string> myList;
}
That's what properties are for in C#:
public class MyClass
{
private List folderList;
public List FolderList
{
get {return folderList;}
set {folderList = value;}
}
}
Properties encapsulate the private fields, provide possibilites for validation while setting. Also, you should read up on Generics (abit like templates in c++) and use List<T> instead of List to have a strongly typed collection.
However, you probably wont be able to achieve what you plan unless Setup derives from MyClass. In that case, you can use a protected field.
We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible, why is this?
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.SeePrivatePropertiesAndFields(s2);
}
}
public class Student {
private String _studentsPrivateField;
public Student() {
_studentsPrivateField = DateTime.Now.Ticks.ToString();
}
public void SeePrivatePropertiesAndFields(Student anotherStudent) {
//this seems like these should be private, even from the same class as it is a different instantiation
Console.WriteLine(anotherStudent._studentsPrivateField);
}
}
Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?
There's an easy way to ensure this:
Don't mess around with private members of other instances of the same class.
Seriously - you're the one writing the Student code.
The easiest way to ensure this is to program to an interface, such as:
class Program
{
static void Main(string[] args)
{
IStudent s1 = new Student();
IStudent s2 = new Student();
s1.ExamineStudentsMembers(s1);
}
}
public interface IStudent
{
void ExamineStudentsMembers(IStudent anotherStudent);
}
public class Student : IStudent
{
private string _studentsPrivateMember;
public Student()
{
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(IStudent anotherStudent)
{
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
This will no longer compile due to ExamineStudentsMembers trying to access a private field.
If you are writing the class, you have complete control over it, so if you don't want one object to be able to modify another, don't write in that functionality.
Classes will often use private variables in other instances to implement efficient comparison and copy functions.
Private just means that the member (field/method/etc.) can be accessed only from the within the code of the parent type. From CSharpOnline
Private members of multiple instances are visible and can be invoked. This comes in handy when you are implementing a "copy constructor" or a "clone" method on your type, where the argument is an instance of the same type. If the designers would have made private fields inaccessible, then you may have to create a bunch of getter methods just for clone/copy to get at them. IMHO, I like it better the way it is. Within the same type, Reading another object's state isn't that bad as writing to it though (which could be a DONT-code-convention for you/your team.)
Accessing a sibling's private data may seem wrong when phrased like:
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
However, it doesn't seem so odd for methods which require this sort of functionality. What methods require accessing a sibling's private data? Comparison methods (in particular equals) and objects in a data structure (say a tree or linked list).
Comparison methods often compare private data directly rather than just the public data.
For a class of nodes that make up a linked list, graph or tree, being able to access a sibling's private data is exactly what is needed. Code in the know (part of the class) can tinker around with the data structure, but code outside of the data structure cannot touch the internals.
It is interesting to note that these two cases are less common in day-to-day programming than when this language feature were first developed. Back in 1990s and early 2000s, in C++ it would have been much more common to build custom data structures and comparison methods. Perhaps it is a good time to reconsider private members.
i like the second point, you can look, but dont touch those private members.
it's funny you should say that, i knew a teacher once and he said he often had a problem deciding what classes it was ok to look at the members and which ones he could actually have a play with.
An object is just a piece of data; the class contains the functionality. A member method is just a nice trick the compiler plays; it's really more like a static method with an implied argument (sort of like extension methods). With that in mind, protecting objects from each other doesn't make any sense; you can only protect classes from each other. So it's natural that it works that way.
No, this is necessary, the method code is not specific to the instance, it is only specific to the type of the object. (virtual methods) or the declared type of the variable (for non-virtual methods). The non-static fields, on the other hand, are instance specific... That's where you have instance-level isolation.
The only difference between a static method and a non-static method is that the static method is not allowed to access other instance based (non-static) methods or fields. Any method that CAN be made static without modification will not be affected in any way by making it static, except to force compiler to throw errors anywhere it was called using instance-based syntax.
If you intend to examine a given student's information then I would change the method to be static:
public static void ExamineStudentsMembers(Student student)
{
Console.WriteLine(student._studentsPrivateMember);
}
You would then use Student.ExamineStudentsMembers(s1). Using s1.ExamineStudentsMembers(s2) would be invalid.
If this isn't the intended purpose I would rewrite the method as:
public void ExamineStudentsMembers()
{
Console.WriteLine(_studentsPrivateMember);
}
The above would then be used by writing s1.ExamineStudentsMembers()
Private members are to hide implementation details from clients. The clients should only see the interface (public methods / fields / properties).
The purpose is not to protect the programmer from himself.
This is also NOT a security feature because you can always access private fields via reflection.
It's really to separate interface & implementation (black box design), and clients programming against a contract (all public fields).
For example if you have a public get property, it could access some private field directly, or it could calculate the value from some other fields.
The purpose is, the client only knows the contract (the public property) and the implementation can be changed without affecting the client
Object scope does not ever imply security - ever! It is role of the OS to provide runtime security. It is a bug to design a system that relies on language specific object scope to limit runtime object instance data access. If this were not the case, then all non OO languages are, by definition, not secure.