C# .NET - How to access private variable to the another class in C# without using public?

Asked By Nilima Patil on 01-Oct-12 12:44 AM
Hi...
Actually Interviewer ask me this question?
suppose..
Class A
{  
    Private variable A;
}
Class B
{
   Want Access?How?
}

please help me ?
How to Access private variable to the another class without using public in C#?
reply me ..

thanking you..

Raman S V replied to Nilima Patil on 01-Oct-12 01:06 AM
Hi,
Private variables in ClassA cannot be accessed from ClassB. They cannot be accessed through objects of ClassA.
We can access them by creating Public properties.

E.g. : In your case :

Create a property like below :

public int A
{

get {return A;}

set
{
//Put any logic here if you have any validations on the variable.
A=value;
}

}

Using only get , will give a read-only property and can be accessed through the objects of ClassA and by usign set, you can also write values.

Hope this answers the question.


Regards,
Raman S V
Jitendra Faye replied to Nilima Patil on 01-Oct-12 01:17 AM
You can not access private member of the class outside,, for this you need to make it protected and then using inheritance you can access it.
Hemanth Kumar replied to Nilima Patil on 01-Oct-12 01:21 AM
You can't access the Private Members Out side a Class.If you want to use declare 'public'  or declare 'protected' and inherit the class then you can access.
Nilima Patil replied to Jitendra Faye on 01-Oct-12 01:41 AM
I told these both options but interviewer said that in C# there is one more option and which is this?
Nilima Patil replied to Hemanth Kumar on 01-Oct-12 01:42 AM
I told these both options but interviewer said that in C# there is one more option and which is this?
Hemanth Kumar replied to Nilima Patil on 01-Oct-12 01:45 AM
Nilima,

According to your Question the Anwser is Right.I suggest you to do a sample example using the Access Specifiers.

Cos mos replied to Raman S V on 01-Oct-12 04:34 AM
Hi, Using reflection you can access the any property or method irrespective of access specifiers.