user2312610
user2312610

Reputation:

Exclusive contracting between two classes or interfaces

I'm wondering if it's possible to define a method or property that only specified classes can interact with or see.

For example:

class Thing
{
    protected int i;
    public virtual int I
    {
        get
        {
            return i;
        }
    }
}
class OtherThing
{
    public virtual void ChangeI(Thing thing, int i)
    {
        thing.i = i;
    }
}

Here, I want OtherThing to be able to access i, or a protected set method for I in Thing, despite being defined outside the scope of Thing.

I recognize that I could simply declare OtherThing inside the scope of Thing, which would then have permission to access protected items, however I would also like this to work with interfaces, whose implementations cannot be defined within the scope of the original interface, and who can't declare protected methods anyway.

This may not strictly be possible, but I'd love to hear of similar ways to achieve the same thing, just so I can do some experimentation on my own.

Thanks in advance.

Upvotes: 1

Views: 58

Answers (2)

Anton Sizikov
Anton Sizikov

Reputation: 9240

When I read the question it feels pretty much like a Visitor pattern: http://www.dofactory.com/net/visitor-design-pattern

Let's say that you have a visitor:

class Program
   {
       static void Main(string[] args)
       {
           var thing = new Thing();
           var otherThing = new OtherThing();
           thing.Accept(otherThing);
           Console.WriteLine(thing.I);
           Console.Read();
       }
   }

   class OtherThing
   {
       public void Change(Action<int> setI)
       {
           setI(42);
       }
   }

   class Thing
   {
       private int i;

       public int I { get { return i; } }

       public void Accept(OtherThing visitor)
       {
           visitor.Change(SetI);
       }

       private void SetI(int i)
       {
           this.i = i;
       }
   }

So the idea is: when you accept the visitor you give it a delegate which can change your private field.

I don't really understand the reason, so my example is very artificial. Anyway you can add interfaces to abstract the things, even use some kind of command to pass instead of an Action. But the idea will stay the same.

Upvotes: 1

wigy
wigy

Reputation: 2222

You are probably looking for the friend-class concept from C++ in C#. C# does not have such a feature on a class-level, so you need to find another design alternative.

Upvotes: 1

Related Questions