The question of why there are no friends in C# has been extensively discussed.
I have the following design problem.
I have two classes TradingSystem and Order. TradingSystem class has only one public function AddOrder(Order ord). Clients are allowed to call only this function. All other logic must be hidden. Order class is listening to market events and must call other other function of TradingSystem ExecuteOrder, so I have to make it public as well. Doing that I will allow clients of Trading system to call this function and I don't want that.
UPDATE Order class and TradingSystem are living in separate assemblies. Order class is base class and many other classes can be derived.
class TradingSystem
{
// Trading system stores list of orders
List<Order> _orders;
// this function is made public so that Order class can call it when need
// but other class must not call it
public ExecuteOrder(Order ord)
{
// some logic
}
// this function is made public for external clients
public AddOrder(OrderRequest ordreq)
{
// omitted code
// create order and pass it this
order.OnOrderAdded(this);
}
}
class Order
{
// reference to TradingSystem class is stored to call it methods
TradingSystem _ts;
public void OnOrderAdded(TradingSystem ts)
{
_ts = ts;
}
// this function is called on timer
void OnMarketEvent()
{
if(/*some logic*/)
_ts.ExecuteOrder()
}
}