user2081328
user2081328

Reputation: 169

How to restrict class members to only one other class

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?

Upvotes: 4

Views: 1649

Answers (6)

Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5524

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

Upvotes: -1

user1770543
user1770543

Reputation: 25

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.

Upvotes: 0

James World
James World

Reputation: 29776

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! :)

Upvotes: 0

kmatyaszek
kmatyaszek

Reputation: 19296

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

Upvotes: 2

AndySavage
AndySavage

Reputation: 1769

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

Upvotes: -1

Servy
Servy

Reputation: 203814

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

Upvotes: 4

Related Questions