tags:

views:

118

answers:

3

I've got two classes : Unit and User.

a Unit class has a User as leader, and a User can be part of many units.

class Unit
{
   User Leader;
   public void SetLeader(User leader)
   {
      this.Leader=leader;
   }
}

class User
{
   Unit UnitLed;
   public void LeadUnit(Unit unit)
   {
      this.UnitLed=unit;
      unit.SetLeader(this);
   }
}

Howw can I enforce it so that a developer using these classes DOES NOT mistakenly call a code such as :

User _user=new User();
Unit _unit=new Unit();
_user.LeadUnit(_unit);
_unit.SetLeader(_user);

but that people use the classes in this way :

_user.LeadUnit(_unit)

+5  A: 

It depends on how you are deploying this code, but you could make SetLeader internal instead of public, so any code outside your assembly cannot call it.

Rex M
+2  A: 

Change your LeadUnit method as this...

class User 
{ 
   Unit UnitLed; 
   public void LeadUnit(Unit unit) 
   { 
      if ( this.UnitLed != unit)
      {
          this.UnitLed=unit; 
          unit.SetLeader(this); 
      }
   } 
} 

You can also enforce similar conditions in the SetLeader method too.

The King
+1  A: 

Unfortunately .Net does not have a way to do this easily.

However you can achieve it by putting the classes in a 2nd project, linked to the main solution, and mark SetLeader internal.

Will