inheritance of private members in c# - c#

Are private members inherited when inheriting the class in c#?
I have read some topic related to this, somebody telling that private members are inherited but cannot access the private members, somebody telling that it is not inherited when inheriting the class. Please explain the concept. if it is inheriting can any body give an explanation?
thanks

If I understand your question correctly then you're not concerned about the accessibility you are only concerned about private members are inherited or not
Answer is yes, all private members are inherited but you cant access them without reflection.
public class Base
{
private int value = 5;
public int GetValue()
{
return value;
}
}
public class Inherited : Base
{
public void PrintValue()
{
Console.WriteLine(GetValue());
}
}
static void Main()
{
new Inherited().PrintValue();//prints 5
}

You can mark things as protected, in which case you can access them from derived types.
Edit: In terms of whether they inherit, then yes they do. The child class is still of the parent classes type, and thus inherits everything. The child just cannot access it directly, but if you call base class methods that use the private parent field, that would work fine.

Private members can't be inherited, only protected which are like extended private members.

Like Sriram says, yes, private members do get inherited, but they ar enot accessible.
If they would not get inherited, protected or public properties references private members would break in inherited classes.
class myBase
{
private string _myProp;
protected string MyProp
{
get
{
return _myProp;
}
set
{
_myProp = value;
}
}
}
class myChild : myBase
{
public myChild()
{
_myProp = "SomeString"; // This will fail!!!
this.Myprop = "SomeString"; // This works
}
}
Here in the child class, you cannot access _myProp directly as it is private in the base class. However, the memeber is inherited, so it is accessible through the protected property MyProp.

Members marked as private can be accessed only on the type where they are defined. You cannot access them from derived types.
Members marked as protected can be accessed on the type where they are defined and on derived types.
Members marked as internal can be accessed only from the assembly where the type is defined.
You may combine the protected and the internal access modifier.
When talking about values of private members: Of course they are inherited. A derived class always also is of the type of the base class. If the base class holds a private value to store some data, the derived class will do that, too - only that you can't access that value from the derived class.
Please also read the relevant article on Accessibility Levels in the MSDN.

What you said about private fields being inherited is totally right.
Here what happens: A subclass will inherit the behaviour of your base class. That behaviour might need some fields to work. So, your subclass will reserve some space for them, but you will not be able to manipulate those fields, only by using methods (public and protected ones)
In other words, your sub class inherits base class fields by holding them in memory, but it cannot access them.
On low level, it is your compiler that prevents you from accessing/changing those private fields, but even using reflection you can still do so.
If you need any clarification, let me know

From http://msdn.microsoft.com/en-us/library/ms173149.aspx
A derived class has access to the public, protected, internal,
and protected internal members of a base class. Even though a
derived class inherits the private members of a base class, it
cannot access those members. However, all those private members are
still present in the derived class and can do the same work they would
do in the base class itself. For example, suppose that a protected
base class method accesses a private field. That field has to be
present in the derived class in order for the inherited base class
method to work properly.

To expand on what's been said, privates can be accessed by a subclass when inner scope is in play. For example, the following will compile:
class A
{
private int _private;
class B : A
{
void Foo()
{
this._private = 2;
}
}
}

Short answer: yes, but you are unable to access them directly.
When class A is derived from class B, and B has a private property then that property will be there for an instance derived of class A. You are, however unable to access it. It must be there because the behavour specified in class B depends on it.
funfact:
It is actually possible to still access the private property with a thing called reflection. But don't worry about that and you should not use reflection for this purpose unless you really need to know what is going on and what you're doing.

The simplest answer you can not access the private variables of base class in derived class directly but yes this private objects and values are initialized in base class when overriding class object is initiated (thus base class variables are inherited) and you can access them using some property or function if base class exposes them.
To make explanation more clear,
class A
{
private int i;
private int j;
protected int k;
public A()
{
i = j = k = 5;
}
}
class B : A
{
private int i; //The same variable exist in base class but since it is private I can declare it
private int j;
private int k; //Here I get warning, B.k hides inherited member A.k'. Use the new keyword if hiding was intended. F:\Deepak\deepak\Learning\ClientUdpSocketCommunication\ClientUdpSocketCommunication\Program.cs 210 25 ClientUdpSocketCommunication
private int l;
private int m;
private int n;
public B()
{
i= j = this.k = l = m = n = 7; // Here I have used this.k to tell compiler that I want to initialize value of k variable of B.k class
base.k = 5; //I am assigning and accessing base class variable as it is protected
}
}
If an object of class B is initialized then, A.i, A.j, A.k variable will be initialized, with B.i, B.j, B.k, B.l variables and if base class exposes function or properties then I can access all the base class variables.

Related

Abstract and concrete classes - getters and setters

How can I use setters in the concrete class? I have two abstract classes and the bottom concrete class should be able to set all the private variables I have the abstract classes, how can I do that?
I could just add getters and setters in my concrete class, but because I have 4 derived classes from my second abstract class, I don't want to have duplicate code and a long list of public properties, any way to resolve that?
I am working in C#
Using the protected keyword in c# you can access the variables in parent objects
Like this
public abstract class Parent {
protected int integer {get;set;}
}
public class Child : Parent {
public Child(int value) {
integer = value;
}
public int getValue() {
return integer;
}
}
see : https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected
From Microsoft documentation :
private
The type or member can be accessed only by code in the same class or struct.
protected
The type or member can be accessed only by code in the same class, or in a class that is derived from that class. internal The type or member can be accessed by any code in the same assembly, but not from another assembly.
private protected
The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
So doesn't matter if the class is abstract or not, private can only be accessed within the same class.

How to choose between private and protected access modifier to encapsulate members between base and childs classes?

I am trying on a project to use private values in my internal functions. In past I used only public ones, but I noticed that obfuscation is working much better when using as much as possible private parameters.
My question is regarding Parent/Child classes.
In my main class I define all the parameters as following :
public class MyFatherClass
{
private long id = -1;
public long ID { get { return this.id; } set { this.id = value; } }
...
}
So in all internal functions I access to my private value instead of the public one.
Then in my daughter class I just add parameters specific to the child class.
public class MyChildClass : MyFatherClass
{
private long anotherParameter = -1;
public long AnotherParameter { get { return this.anotherParameter; } set { this.anotherParameter = value; } }
...
}
Just, I see that in my Parent class, I can access to id and ID without problem, but from daughter classes I can only access ID(as id is private).
If I understood correct, I would need to replace all private by protected in my parent lass, so it would solve the problem?
What I don't understand is the code is working even if I leave it so.
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
I am now hesitating, may I just add a private id in each child class, or may I set id to protected in my parent class?
Thanks for your explanations.
Edit, just adding a screenshot of my reversed code after obfuscation, so you could understand difference on how are obfuscated private/public methods/fields
Why don't I have an error message, when I set ID value in daughter class, the sentence this.id=value is executed, but how can can I access to it from my child class if it is private?
When you call a public method on a class, that method can access private members of that class:
public class Foo
{
public void Bar()
{
Baz();
}
private void Baz()
{
// private method called by public method
}
}
var foo = new Foo();
foo.Bar();
This compiles just fine. Your setter is the same: it's public, so callable from everywhere, even if it accesses private members.
As for making your field (private long id = -1;) protected: yes, that will mean you can access it in derived classes. But whether you want to is another question.
You have declared a public property for a reason. Perhaps you want to do some validation in its setter or getter. If not, if you're just using a property to access a private field, you could just ditch the entire private field and use an auto-implemented property:
public long ID { get; set; } = -1;
Then you can access the property everywhere, from within itself, from derived classes and from code using this class.
See also:
What is the difference between a field and a property?
What are Automatic Properties in C# and what is their purpose?
Here is a short and reduced description of what access modifiers do:
Public : fields (variables) and properties (variables encapsulation) and methods (functions and procedures) are visible and accessible by the class itslef, by its childs and by any other external classes.
Private : members (fields, properties and methods) are visible and accessible only by the class, not by its childs nor by any external class.
Protected : members are visible and accessible by the class and by its childs, but not by others classes.
Internal : members are visible and accessible by the class and by its childs and by any class that is in the same assembly (.exe and .dll), but not by a class from another assembly.
So you should set id to protected in the parent class to use it in the childs.
But here is the rule:
If childs classes can modify id you should set as a protected field, and offer a public property (get) if available for external items.
If childs classes are not allowed to modify it you should set it private and offer :
A propected property with only a getter if external items can't access it.
A public property with only a getter if external items can access it.
Don't repeat a member with the same name else it will hide the parent and can cause polymorphism problems, else you know what you do.
You can read these tutorials to more understand access modifier keywords:
C# Access Modifiers
Access Modifiers (C# Reference)
Here are some readings:
C# Tutorial Level 0
C# Tutorial Level 1
C# Tutorial Level 2
C# Tutorial Level 3
C# Snippets # Techi.io
Beginning Visual C# 2008 Programming
The MyChildClass class which inherits from the MyFatherClass can not access the id field because it's private. To make it accessible, you will need to change the field's access modifier to either:
protected :
////////////////////////////////////
// Dll1.dll
////////////////////////////////////
namespace Dll1
{
public class Base
{
//The field we are attempting to access
protected int a;
}
public sealed class Main : Base
{
public void DoSomething()
{
//Can be done sins Main inherits from Base
base.a = 100;
}
}
public class Invader
{
public int GetA()
{
var main = new Main();
main.DoSomething();
// can not be done sins the field is only accessible by those that inherit from Base
return main.a;
}
}
}
////////////////////////////////////
// Dll2.dll
////////////////////////////////////
namespace Dll2
{
public class ADll2Class : Dll1.Base
{
public int GetA()
{
//Can be done because ADll2Class inherits from Dll1's Base class
return base.a;
}
}
}
private protected :
Same as protected but, in the example above, Dll2's class, ADll2Class, will not be able to access the a field because it would be privately protected, in other words only classes from the same dll as Base which inherit from Base will be able to access a.
or you can set it to
internal :
If the a field in the example above was internal, then, same as private protected, Dll2's class wont be able to access it but, the Invader class in Dll1 will be able to access it sins it's part of the same dll as Base.
Note that, sins you mentioned obfuscation, try as hard as you will, the id field can still be accessed by others in an obfuscated state with the help of reflection, especially sins you provide a public property ID, might as well set everything in your project to internal.

Concept of Private class in C#

Can private classes exist in C#, other than in Inner classes?
Simply NO. Nothing unless its in a nested Class
Classes and structs that are not nested within other classes or structs can be either public or internal. A type declared as public is accessible by any other type. A type declared as internal is only accessible by types within the same assembly. Classes and structs are declared as internal by default unless the keyword public is added to the class definition.
Class or struct definitions can add the internal keyword to make their access level explicit. Access modifiers do not affect the class or struct itself — it always has access to itself and all of its own members.
Struct members, including nested classes and structs, can be declared as public, internal, or private. Class members, including nested classes and structs, can be public, protected internal, protected, internal, or private. The access level for class members and struct members, including nested classes and structs, is private by default. Private nested types are not accessible from outside the containing type.
Derived classes cannot have greater accessibility than their base types. In other words, you cannot have a public class B that derives from an internal class A. If this were allowed, it would have the effect of making A public, because all protected or internal members of A are accessible from the derived class.
You can enable specific other assemblies to access your internal types by using the InternalsVisibleToAttribute.
No, there isn't. You cannot have a private class unless it is nested.
In what scenario other then for an innter class would you like to have a 'private' class ?
You can use the internal modifier to create a class that is only visible in the current assembly.
// the class below is only visible inside the assembly in where it was declared
internal class MyClass
{
}
No.
What would the scope of such a class be?
We can declare a class as Private inside other class. kindly find the code below on how to achieve the same:
public class Class1
{
temp _temp ;
public Class1()
{
_temp = new temp();
}
public void SetTempClass(string p_str, int p_Int)
{
_temp.setVar(p_str, p_Int);
}
public string GetTempClassStr()
{
return _temp.GetStr();
}
public int GetTempClassInt()
{
return _temp.GetInt();
}
private class temp
{
string str;
int i;
public void setVar(string p_str, int p_int)
{
str = p_str;
i = p_int;
}
public string GetStr()
{
return str;
}
public int GetInt()
{
return i;
}
}
}

Usage of "Class" in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
While studying C# in ASP.net I have trouble understanding several classes. In which scenario should I use the following classes private,public,protected,abstract,static,sealed ?
It would be better if someone can explain these with easy examples.
Those are not classes.
private, protected and public are access modifiers. They indicate which other code can see the code they affect:
public class Foo
{
private int _myOwn = 1;
protected int _mineAndChildren = 2;
public int _everyOnes = 3;
}
public class Bar : Foo
{
public void Method()
{
_myOwn = 2; // Illegal - can't access private member
_mineAndChildren = 3; // Works
_everyOnes = 4; // Works
}
}
public class Unrelated
{
public void Method()
{
Foo instance = new Foo();
instance._myOwn = 2; // Illegal - can't access private member
instance._mineAndChildren = 3; // Illegal
instance._everyOnes = 4; // Works
}
}
An abstract class is one that may contain abstract members. An abstract member has no implementation, so all derived classes must implement the abstract members.
A sealed class cannot be inherited. A static class is sealed, but also can only contain static members.
I suggest you start with "Getting Started with Visual C#. This is a very basic question.
public, private and protected aren't classes, they're access modifiers. They change what is allowed to access the classes that you decorate with them. They apply to classes as well as the members of classes.
public items can be seen from anywhere
private classes can only be seen from within the same file
private members of classes can only be seen within that class
protected members are visible from within the class and its descendants
internal classes are public within the same assembly.
The abstract keyword marks a class or method as having no implementation, and it must be overridden (with the override keyword) in a derived type before you can use it.
A sealed class cannot be inherited from.
Using the static keyword on a class member indicates that the member belongs to the class itself, rather than a specific instance of it. Marking a class as static imposes the restriction that all members of this class must also be static.
private, public and protected indicate who can access members of a class. private means no one outside the class can see it. public means everyone can see it. protected is just like private, but subclasses can access it.
class Data
{
private int counter; // only accessible to class functions
protected int id; // accessible to class and subclass functions
public string name; // accessible from all code
}
abstract means this is not a finished class - it is meant to be used as a base for subclasses. Often there are virtual functions in its definition, functions intended to be "filled in" by a subclass.
abstract class Window
{
// cannot create objects of this class directly
// need to create sub class
}
static on the class definition means there's only one global copy. It pretty much reverts the class to an old-style module. static against a member indicates that it is a global member within the class, there is not a different version for every object you make of that class.
static class Configuration
{
// only one instance of the object
}
class Data
{
private static int counter; // all Data objects access this one counter
private int id; // each Data object has a different id
}
sealed prevents subclasses being created; it can also be applied to individual functions to prevent them being overridden in a subclass.
sealed class TelephoneNumber
{
// cannot create subclass of TelephoneNumber
}
class Address
{
public sealed string FormatAddress()
{
// this function cannot be overridden on a subclass
}
}
I down't can comment your question but i have an little adition but importan information for you.
access modifiers are only an compiler-feature. every .net-programm can ignore this by using reflection and can access your private flaged classes and methodes.
An exampel:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectPrivateMembers
{
class Program
{
static void Main(string[] args)
{
ConstructorInfo ci = typeof(Hello).GetConstructor(BindingFlags.NonPublic| BindingFlags.Instance ,null,System.Type.EmptyTypes,null);
object helloObject = ci.Invoke(System.Type.EmptyTypes);
MethodInfo[] helloObjectMethods = helloObject.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly| BindingFlags.Instance );
foreach (MethodInfo mi in helloObjectMethods)
{
mi.Invoke(helloObject, System.Type.EmptyTypes);
}
Console.ReadLine();
}
}
public class Hello
{
private Hello()
{
Console.WriteLine("Private Constructor");
}
public void HelloPub()
{
Console.WriteLine("Public Hello");
}
private void HelloPriv()
{
Console.WriteLine("Private Hello");
}
}
}
Source: Reflection with Private Members
The first three are access modifiers, they can be applied to types and members.
private means something can only be accessed from within its declaring type.
protected means something can be accessed by inheritors of the declaring type, or by something in the type itself.
public means something can be accessed from anywhere that has a valid reference to the declaring type.
The rest can also be applied to both types and members.
abstract (on a member) means the member has no implementation (the implementation must be provided by inheritors of the type) or (on a type) that the type cannot be instantiated (only inherited).
static (on a member) means that the member is shared statically by all callers, or (on a type) that the type can only contain static members and therefore cannot be instantiated (i.e. it doesn't have any instance members and therefore cannot serve any instances of itself).
sealed (on an inherited virtual or abstract member) means that inheritors of the type cannot override the member, or (on a type) that the type cannot be inherited from.
There are a couple of other modifiers you should be aware of:
internal is another access modifier that means that something can be accessed by anything within the same assembly (or project) as the declaring type.
Also,
virtual (on a member) means that the member may optionally be overridden by an inheritor of the type, but supplies its own default implementation.
partial (on a member) allows you to provide the signature of a member in one file, and the implementation in another, or (on a type) allows you to split the definition of a type across multiple code files.
What you have there are modifiers, not types of classes.
private, public, and protected are Access Modifiers. They define how accessible you want the code to be.
Before looking into the other modifiers you have listed, I would suggest attempting to get a grasp on Object Oriented Programming. Here is a link full of good resources you can review.
private,public,protected are the access modfier supported by c# language : here is the msdn link for more detail Access Modifiers
Abstract and Sealed Classes and Class Members
Static Classes and Static Class Members
private and public refer to the visibility of the class outside the assembly (e.g. DLL or EXE) it lives in. protected is a modifier for methods, it means only classes that inherit from the declarator can call the method.
abstract identifies a class that cannot be created directly, and is designed only to provide a base for other classes.
Applied to methods, static means they can be accessed as part of the type, rather than an instance of the class:
class Bar {
static void Foo() { ... }
void Foo() { ... }
}
The first one can be called like this:
Bar.Foo();
The second one only like this:
Bar b = new Bar();
b.Foo();
Applied to classes, static limits the class to contain only static methods. It's more aesthetic than anything else, but it also helps the compiler.
The sealed modifier tells the compiler that a class cannot be inherited from.

Are private members inherited in C#?

Just seen one tutorial saying that:
Class Dog
{
private string Name;
}
Class SuperDog:Dog
{
private string Mood;
}
Then there was an UML displaying that SuperDog will inherit Name as well. I have tried but to me it seems that only public members are inherited. At least I could not access Name unless it was declared as public.
A derived class has access to the
public, protected, internal, and
protected internal members of a base
class. Even though a derived class
inherits the private members of a base
class, it cannot access those members.
However, all those private members are
still present in the derived class and
can do the same work they would do in
the base class itself. For example,
suppose that a protected base class
method accesses a private field. That
field has to be present in the derived
class in order for the inherited base
class method to work properly.
From: http://msdn.microsoft.com/en-us/library/ms173149.aspx
So, technically, yes, but practically, no.
Everything from the base class is
inherited to derived class. members
marked private are not accessible to
derived classes for integrity purpose,
should you need to make them
accessible in derived class, mark the
members as protected.
There are various levels of members' accessibility in context of inheritance.
public: all public members of the base-class are accessible within the derived-class and to the instances of derived-class.
protected: all protected members of the base-class are accessible within the derived-class and not to the instances of derived-class.
protected internal: all protected internal members of the base-class are accessible within the derived-class and to the instances of derived-class created within the same assembly.
internal: all internal members of the base-class are accessible within the derived-class and to the instances of derived-class within the same assembly.
private: no private members of the base-class are accessible within the derived-class and to the instances of derived-class.
private protected: The type or member can be accessed only within its declaring assembly, by code in the same class or in a type that is derived from that class.
SuperDog will inherit the Name field, yes.
SuperDog will NOT have access to the field though, so there is no practical use (as far as SuperDog is concerned).
Private members can be visible inside a derived class: (If the subclass is nested within the base class)
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!";
}
}
}
Credit for the example goes to KodefuGuru in this thread at MSDN.
Yes, although heirs cannot access that member.
If you with that they will be able to access it, declare it as protected.
No, they aren't.
The protected modifier can make fields available to derived classes, but this is generally considered a bad idea from a maintenance perspective. You'd want to use protected properties instead.
try the keyword protected, instead of public/private:
http://msdn.microsoft.com/en-us/library/bcd5672a(VS.71).aspx
Make Name protected or public instead, that will be accessible. Private members are not accessible from derived classes
Private members are not accessible to descendants of a class.
I'm not sure of all the access modifiers, but at the most basic only public and protected members are accessible.
Yes, The are inherited.
But you cannot access them as they are private :).
As others have said private members are inherited. Member access is a different subject but not totally disjoint from an inheritance perspective. It is important to understand that all members are inherited regardless of their access modifier because it effects the sizes of the subclasses. Consider the following code.
public class Foo
{
private int a;
public int b;
}
public class Bar : Foo
{
private int c;
public int d;
}
Foo will consume 16 bytes on the heap. 4 for the syncblock, 4 for the type information (method table), and 4 each for the int variables for a total of 12. Bar, on the other hand, will consume 24 bytes. 4 for the syncblock, 4 for the type information (method table), 4 each for the int fields inherited from Foo, and 4 each for the int fields in Bar for a total of 24.
People have said it, but here's an example of why you need the private fields in the derived class:
class Program
{
static void Main(string[] args)
{
var r = new Random();
foreach(var i in Enumerable.Range(0,100))
new Derived(r).Printer();
Console.Read();
}
}
public class Base
{
private Random r;
public Base(Random r) { this.r = r; }
protected void Print()
{
Console.WriteLine(r.Next(1, 10000));
}
}
public class Derived : Base
{
public Derived(Random r) : base(r) { }
public void Printer()
{
base.Print();
}
}
You are right, private members aren't accessible by the derived class.
You should either make the members protected or access them using the public methods of the base class.
class Player
{
protected string name;
protected string type;
public Player(string name,string type)
{
Console.WriteLine("Player"+ this);
this.name = name;
this.type = type;
}
public void introduce()
{
Console.WriteLine("I am " + this.name + " I'm a " + this.type);
}
}
class Wizard : Player
{
public Wizard(string name,string type):base(name,type)
{
Console.WriteLine("Wizard"+ this);
}
public void Play()
{
//protected modifier made the name field available;
Console.WriteLine("Yipeeee!!!!!"+ " "+ this.name);
//on the other hand
// we can make the name and type fields as private in the base class and access them using the public methods of the base class
introduce();
}
Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But yes they really are

Categories