Concept of Private class in C# - 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;
}
}
}

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.

Understanding Access specifiers on Classes in C#

First of all let me start by saying that I do understand access specifiers I just don't see the point of using them in classes. It makes sense on methods to limit their scope but on classes, why would you want a private class, isn't it the purpose of classes to be able to reuse them?
What is the purpose of access specifiers when declaring a class in C#? When would you use them?
Thanks
Well, let's say that you want a class to be only accessed inside her own assembly:
internal class Test
Let's say that you have two classes, one inside the other (nested classes):
protected internal class TestA
{
private TestB _testB;
private class TestB
{
}
public TestA()
{
_testB = new TestB();
}
}
The TestB class can be only accessed inside methods/properties/contructors inside TestA or inside herself.
The same applies to the protected modifier.
// Note
If you don't specify the access modifier, by default it will be private, so on my example the following line:
private TestB _testB;
is equal to
TestB _testB;
And the same applies to the class.
Special Modifier
Then, there is the protected internal which joins both modifiers so you can only access that class inside the same assembly OR from a class which is derived by this one even if it isn't in the same assembly. Example:
Assembly 1:
public class TestA : TestB
{
public TestB GetBase()
{
return (TestB)this;
}
public int GetA1()
{
return this.a1;
}
}
protected internal class TestB
{
public int a1 = 0;
}
Program
TestA _testA = new TestA(); // OK
TestB _testB = new TestB(); // ERROR
int debugA = new TestA().a1 // ERROR
int debugB = new TestA().GetA1(); // OK
TestB testB_ = new TestA().GetBase(); // ERROR
Source
Link (Access Modifiers)
Internal
The type or member can be accessed by any code in the same assembly,
but not from another assembly.
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
struct, or in a class that is derived from that class.
Public
The type or member can be accessed by any other code in the same
assembly or another assembly that references it.
I will give you an example of an internal class. Imagine I have some DLL. Form this DLL I want to expose only a single class called A. This class A however, should have access to other classes inside DLL - thus I will make all other classes inside DLL internal. Hence, from the DLL you can only use class A, while A can still access other classes inside DLL - you however, can't.
The greatest benefit of using access specifiers is when someone else is using your classes. By clearly specifying, what should and what should not be touched within your objects, you can protect your object internal mechanism and integrity from being misused or damaged.
With bigger classes, if you made everything public, you would also make it harder for the user of your code to work with IntelliSense, which is something that is very handy when you deal with unknown libraries.
I have created one application to understand Access Specifiers.
It will be more easy to understand it with code instead of Theory.
I have added my notes in code, for better guidance.
namespace ConsoleApplication1
{
//A normal public class which contains all different types of access-modifier classes in the assembly named 'ConsoleApplication1'
public class Base
{
public class PublicBase
{
public static void fn_PublicBase()
{
Console.WriteLine("fn_PublicBase");
}
}
private class PrivateBase
{
public static void fn_PrivateBase()
{
Console.WriteLine("fn_PrivateBase");
}
}
protected class ProtectedBase
{
public static void fn_ProtectedBase()
{
Console.WriteLine("fn_ProtectedBase");
}
}
internal class InternalBase
{
public static void fn_InternalBase()
{
Console.WriteLine("fn_InternalBase");
}
}
protected internal class ProInternalBase
{
public static void fn_ProInternalBase()
{
Console.WriteLine("fn_ProInternalBase");
}
}
//TIP 1:This class is inside the same class 'Base' so everything is accessible from above.Hurray!!
class Base_Inside
{
public static void fn_Base_Inside()
{
//All methods are easily accessible.Does not consider a modified indeed.
PublicBase.fn_PublicBase();
PrivateBase.fn_PrivateBase();
ProtectedBase.fn_ProtectedBase();
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
//Different class but inside the same assembly named 'ConsoleApplication1'
public class Base_Sibling : Base
{
//TIP 2:This class is NOT in same class 'Base' but in the same assembly so only protected is NOT accessible rest all are accessible.
public void fn_Base_Sibling()
{
PublicBase.fn_PublicBase();
//PrivateBase.fn_PrivateBase(); //ERROR:Accesibility of 'protected'
ProtectedBase.fn_ProtectedBase(); //protected is accessible because Base_Sibling inherit class 'Base'. you can not access it via Base.ProtectedBase
InternalBase.fn_InternalBase();
ProInternalBase.fn_ProInternalBase();
}
}
}
Now to Understand difference between internal, protected internal,
I Have added one for project named with Assembly_1 in same
solution.
I have inherited Base class of ConsoleApplication1 to Derived class of Assembly_1.
namespace Assembly_1
{
//TIP:if it does not inherit class 'ConsoleApplication1.Base' then we can not access any thing beacuse this is different assembly.
//TIP:only INTERNAL is NOT accessible , rest all are accessible from first assembly if it inherits class 'Soul'
public class Derived : ConsoleApplication1.Base
{
public class PublicDerived
{
public static void fn_PublicDerived()
{
PublicBase.fn_PublicBase(); //YES, becuase this is 'public'
//PrivateBase.fn_PrivateBase(); //No, becuase this is 'private'
ProtectedBase.fn_ProtectedBase(); //YES, becuase this is 'protected'
//InternalBase.fn_InternalBase(); //No, becuase this is 'internal'
ProInternalBase.fn_ProInternalBase(); //YES, becuase this is 'protected internal'
}
}
}
}
- Update answer 2019 -
Hi You can find accessibility via below table

Can a nested/inner class see the private members of its containing/outer class?

I had this impression that a nested class could access the private members of a containing class and I don't remember why I believed this.
Is this true? And if it is, I've forgotten the syntax to use to access the outer class' members from within a nested class.
A nested Class has access to the private Members of it's containing type:
Class T{
private static void Foo(){
// do sth.
}
public class InnerClass{
public static void Bar(){
Foo(); //no Problem.
}
}
}
Yes; from Nested Types (C# Programming Guide):
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.

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.

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