3

I want to access class members that are in Class1 from another class (Class2) but I want to access it just from that class and to forbid access form any other class, form, etc. Is there any way to do this?

Servy
  • 202,030
  • 26
  • 332
  • 449
user2081328
  • 159
  • 3
  • 15

6 Answers6

4

The only way to do this is to nest the classes, and then make the data private:

public class Class1
{
    private object data;
    public class Class2
    {
        public void Foo(Class1 parent)
        {
            Console.WriteLine(parent.data);
        }
    }
}
Servy
  • 202,030
  • 26
  • 332
  • 449
2

You can use nested class with private scope:

public class Class2
{
    public Class2()
    {
        Class1 c1 = new Class1();
        Console.WriteLine(c1.Id);
    }                

    private class Class1
    {
        public int Id { get; set; }
    }
}
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
  • The question seems to indicate that both classes should be public but that any other classes can't access the instance data of either. This doesn't accomplish that. This prevents access to `Class1` entirely from any other type. – Servy Dec 04 '13 at 18:46
  • I think that he/she want to prevent access to class (`Class1`) members at all. This question doesn't specify, if `Class1` can be used by other classes than `Class2`. – kmatyaszek Dec 04 '13 at 18:56
0

Actually, you can do this with a bit of lateral thinking. One way is to create a method on Class1 that accepts an instance of Class2 and returns delegates to access the members which are marked private. Then declare Class2 as sealed to prevent someone sneaking in with inheritance.

Another way would be to inspect the call stack with a StackFrame in each member (fields are out for this) and throw an Exception if the caller isn't the desired type.

Lord knows.why you'd do this though! :)

James World
  • 29,019
  • 9
  • 86
  • 120
0

You can make an interface, that expose properties for access to your private members. And implement it explicitly. Than use that interface in other class. 2-nd way is to use reflection. 3-rd is nested classes.

-1

You want a c# equivalent of "friend", but there isn't really one. This previous question gives possible solutions.

Community
  • 1
  • 1
AndySavage
  • 1,729
  • 1
  • 20
  • 34
-1

you may implement a property

[IsAllowed(true)]
public class a
{

}

then at your,method you may change the sign of each method requiring the instance.

public class b {
   public void method ( object aClassInstace){
     .... Here check the property
   }
}
Juan Pablo Gomez
  • 5,203
  • 11
  • 55
  • 101