ali_bahoo
ali_bahoo

Reputation: 4863

Suggestions to Ensure Encapsulation

In my solution I have a DLL project, say Project1, that owns a class, say class A. This class has some properties, so vital that must only be set in this DLL. Any other projects that references this DLL can only use the getters. So far I have handled the situation by accessing the setters internally, like:

public class A
{
  int Num1 
  {
    get; 
    internal set;
  }

  int Num2 
  {
    get; 
    internal set;
  }
} 

Right now I have to add another project, Project2, to the solution that not only must use class A (both getters and setter) but also, Project1 has a reference to this new project. So I decided to separate class A in a different definition dll, on the top of the hierarcy. That is the point, my problem araises. Now all the setters are invisible to Project1 and Project2. If I remove the internal accessor then setters will be available to any assembly that references the definition dll. I do not want this because the information on the class A is so important, it must not be set mistakenly.

How can I limit the access to the setters of class A from outside of Project1 and Project2?

Only solution comes to my mind is using InternalsVisibleTo. I do not know, it doesn't sound perfect. Also combining Project1 and Project2 would be another another solution, but these two are responsible for completely different tasks, it is not the best option designwise.

Upvotes: 2

Views: 108

Answers (3)

Yahia
Yahia

Reputation: 70369

you could always do something like this (a nightmare of a design but does what you asked for):

public class A
{
  int _Num1, _Num2;

  int Num1 {get {return _Num1;}; }
  int Num2 {get {return _Nun2;}; }

  protected void SetNum (int pWhich, int pV)
  {
      if ( pWhich == 1 ) {_Num1 = pV; return;}
      _Num2 = pV;
  } 
} 

and then you could instanciate the class normally... when you need to set the values you use reflection:

myClassA.GetType().GetMethod ("SetNum", BindingFlags.NonPublic ).Invoke (myClassA, new object[] {1, 777 });

Upvotes: 0

Mike Richards
Mike Richards

Reputation: 5667

You can keep the internal protector on it, but give another assembly the trust to access the internal members.

[assembly: InternalsVisibleTo("AssemblyName")]

You can do this at the class level, or on the entire assembly itself if you want.

InternalsVisibleToAttribute Class

Upvotes: 2

Tullo_x86
Tullo_x86

Reputation: 2673

If I'm right in assuming that Project1 does some specific stuff, and Project2 is an abstraction on top of that, then this is a candidate for inversion of control - ideally, an implementation should depend on an abstraction, not the other way around.

If things within Project2 need to control something defined in Project1, create an interface in Project2 and have Project2 talk to the interface, then implement the interface in Project1 and do all the dirty work internally.

Upvotes: 0

Related Questions