Search code examples
c#classaccess-modifiers

How can I determine the type of object that is allowed to call specific method?


I have a Node class:

public class Node
{
    private string name;
    private Point3D location;
    private int id;
    .
    .
}

and a Graph class:

public class Graph
{
  ....
}

The id in Node is readonly, but I need to set its value only from Graph objects and not from outside the Graph class. How can I accomplish this?


Solution

  • One option that may help (but not totally fix it) is to use the modifier internal on the property. This restricts the accessibility scope of the property to within the assembly it is a member of, and to any assemblies declared as friends.

    Having said that, your requirement to make Id public but changeable only from a Graph object violates OO concepts. A way to work round this is to restrict creation of Node objects to within the Graph class, or from a factory method only available to the Graph class. If you do this and have the Id property exposed as public with only a getter, and assign it a value in the constructor then you will achieve 90% of what you want.