Is there a way to define a field as private but still modifiable within a method using the generic of the containing class?
(Apologies for the length of the question; I am struggling to nail down exactly what I am asking)
Specifically, I currently have three classes A, B, C with the following requirements:
BandChave a field calledname, butAdoes notAandChave a methodLoad(), butBdoes not- Collections of
BandCusenamein a customAdd()method, butAdoes not use this method
This is my current solution:
public class BaseClass
{
public SomeType Load() { ... }
}
public interface IClass {
string Name {get; set;}
}
public class MyList : SomeCollection<IClass>
{
// Depends on x.Name, and may modify Name before adding x to the collection
public new void Add(IClass x) { ... }
}
public class A : BaseClass { ... }
public class B : IClass { ... }
public class C : BaseClass, IClass { ... }
This solution works for me if Name has a public set. But is there some way to properly encapsulate x.Name so that Add can modify x.Name, but x.Name cannot be modified in instances of B and C?
The short answer is no. You cannot selectively expose members to specific classes, and
MyListhas no inheritance relationship withIClass.What you can do, however, is create an additional internal interface (or possibly make
IClassinternal) that exposes theNameproperty and implement it explicitly. This means that in order to read/write theNameproperty, you would need to cast an instance to the internal interface, which would be possible only within the assembly it is defined.Note I’m not using the new keyword to bypass the base class’
Addmethod since this would override the polymorphism (e.g. if you’d cast an instance ofMyListtoIList<IClass>the original implementation ofAddwould be called – and that’s bad.) Instead I’m overriding the appropriate method from theCollection<T>class, which is designed for collection inheritance.