Are private members inherited in C#? - 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

Related

inheritance of private members in 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.

Accessing subclass in base class... but different

I have a base class that has a subclass (could be a struct i suppose but not sure if it's appropriate) and a method.
class Base
{
protected class SubClass
{
public string word;
public int number;
}
protected void SomeMethod()
{
this.SubClass.word //this is where I'm struggling
}
}
Then i have a couple child classes that implement my baseClass, instantiate the Base.SubClass and add some values to the instantiated class.
class ChildClass1 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "WhoFarted";
}
}
class ChildClass2 : Base
{
public childSubClass = new SubClass();
public void DoSomethingRidiculous()
{
childSubClass.word = "ItStinks";
}
}
If possible, I would like to be able to get the value of SubClass.word from within the Base class. I think that my attempt at implementing my idea is probably wrong.
I'm not sure that you really need subclassing / class nesting. Just move out class SubClass declaration and declare protected field/property of SubClass type instead.
public class SubClass
{
public string word;
public int number;
}
public class Base
{
protected SubClass subClassInstance = new SubClass();
protected void SomeMethod()
{
this.subClassInstance.word //this is where I'm struggling
}
}
Then you can access subClassInstance inside both ChildClass1 and ChildClass2
The base class has no field or property of type SubClass, so you definitely cannot do what you propose directly.
One solution would be to add the field
public childSubClass = new SubClass();
to class Base itself. Is there a problem with this?
The other solution would be to use reflection to get the value of the field, assuming that the object you are reflecting on does have such a field. This is really far-fetched and while it might technically allow you to do what you propose, it has a very bad code smell.
I'm not sure why you're making a Sub Class instead of just making those two properties of the base class, but the reason you're having trouble with this line :
this.SubClass.word //this is where I'm struggling
is because you're not instantiating SubClass as a property of the base class.
A base class can not (or should not) access members of derived classes, and usually not even know about derived classes (some exceptions apply, such as in the case of the State Pattern). If the base should have access to a member, it should be declared in the base. If derived classes should also be able to use that member, then mark the member as protected.
class Base
{
protected Foo someFoo;
void Frob()
{
// can access methods/properties of someFoo instance
}
}
class Child
{
public Child()
{
someFoo = new Foo(); // child can also access someFoo
}
}

How do I specify a method that can be accessed only from derived classes of the same assembly?

Is there any way in C# to specify a method that can be accessed only from derived classes of the same assembly without using internal access modifier?
Thanks.
You have to specify both internal as well as protected.
Give the scope of the class as internal
and method scope as protected
Internal class Myclass
{
Protected void MyMethod()
{
//Do something
}
}
Read about C# Protected Internal
protected A protected member is accessible within its class and by
derived classes.
internal Internal types or members are accessible only within
files in the same assembly.
protected internal Access is limited to the current assembly or
types derived from the containing
class.
* protected internal is the only access modifiers combination allowed
for a member or a type.
So you need to use internal key word after all:
protected internal memberName(){ ... };
I believe you can do something like:
public class OriginalClass { ... }
internal class DerivedClass: OriginalClass
{
protected void MemberName() { ... }
}
This way, only internal classes can see the DerivedClass and only internal derived classes can see the portected members inside it.
And also, you still able to access the OriginalClass from everywhere.
Ok! I imagine the situation where you would like to have more flexible control of what assembly class is from, and what class is derived from, than with 'internal' keyword. For example if you wish to check that the object is from th-a-at assembly and derives from one of the-e-e-ese classes.
You can do it through Assembly.GetAssembly() method of the type
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getassembly.aspx
And here is the way to check if object is derived one from another.
Check if a class is derived from a generic class
So you can check all you need.
Then you can implement something like:
public static bool CheckTypeIsCorrect(Type t)
{
if(t.GetAssembly().FullName != AssemblyYouNeed) return false;
if(!(check anything you want in the class)) return false;
return true;
}
...
public void YourMethod(object value)
{
if(!CheckTypeIsCorrect(typeof(value)))
throw ArgumentException("Type of the object is not correct");
...
}
Make the function Access modifier as Protected in your Base Class. Like below
protected void YourFunctionName()
{
//This will be accessible in your derived class only.
}
A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access takes place through the derived class type.
Below is an example from MSDN
namespace SameAssembly
{
public class A
{
protected void abc()
{
}
}
private class B : A
{
void F()
{
A a = new A();
B b = new B();
a.abc(); // Error
b.abc(); // OK
}
}
}

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;
}
}
}

Is there a way to reach a `protected` member of another object from a derived type?

class MyBase
{
protected object PropertyOfBase { get; set; }
}
class MyType : MyBase
{
void MyMethod(MyBase parameter)
{
// I am looking for:
object p = parameter.PropertyOfBase; // error CS1540: Cannot access protected member 'MyBase.PropertyOfBase' via a qualifier of type 'MyBase'; the qualifier must be of type 'MyType' (or derived from it)
}
}
Is there a way to get a protected property of a parameter of a type from an extending type without reflection? Since the extending class knows of the property through its base type, it would make sense if possible.
Last time I faced a similar problem, I used the solution of adding a protected static method to the base:
class MyBase
{
protected object PropertyOfBase { get; set; }
protected static object GetPropertyOfBaseOf(MyBase obj)
{
return obj.PropertyOfBase;
}
}
class MyType : MyBase
{
void MyMethod(MyBase parameter)
{
object p = GetPropertyOfBaseOf(parameter);
}
}
No, you can't do this.
You're only allowed to access protected members of objects of the accessing type (or derived from it). Here, we don't know whether the parameter is of type MyType or SomeOtherCompletelyDifferentType.
EDIT: The relevant bit of the C# 3.0 spec is section 3.5.3:
When a protected instance member is
accessed outside the program text of
the class in which it is declared, and
when a protected internal instance
member is accessed outside the program
text of the program in which it is
declared, the access must take place
within a class declaration that
derives from the class in which it is
declared. Furthermore, the access is
required to take place through an
instance of that derived class type or
a class type constructed from it. This
restriction prevents one derived class
from accessing protected members of
other derived classes, even when the
members are inherited from the same
base class.
There's a good reason you can't do this. Suppose someone writes:
class Other : MyBase { }
new MyType().MyMethod(new Other());
If the language allowed what you're asking for, you could violate the assumed invariants of Other by modifying the value of PropertyOfBase.
I think you should ask yourself if there is a better way of doing what you want to do. You want PropertyOfBase to act as public in the context of MyType.MyMethod(), but to be protected in all other situations. Why?
A protected property is only accessible to an instance of a derived class, not to instances of derived classes.
There is a difference and it does make sense, protected members should not give up their value to any other instance, even an instance derived from the same type.
(Edited, got myself a bit tongue tied!)
As you are inheriting from MyBase, you can access all fields/properties/methods from it marked as "protected" using the "base" keyword.
public class MyBase
{
protected object PropertyOfBase { get; set; }
}
public class MyType : MyBase
{
void MyMethod()
{
object p = base.PropertyOfBase;
}
}
You can also declare MyType as a nested class of MyBase (instead of inheriting), this way you can access private/protected members when you send the class MyBase as a parameter
public class MyBase
{
protected object PropertyOfBase { get; set; }
public class MyType
{
public void MyMethod(MyBase parameter)
{
object p = parameter.PropertyOfBase;
}
}
}
To create an instance of MyType just use
var t = new MyBase.MyType();
t.MyMethod(new MyBase());

Categories