Hiding inherited members - c#

I'm looking for some way to effectively hide inherited members. I have a library of classes which inherit from common base classes. Some of the more recent descendant classes inherit dependency properties which have become vestigial and can be a little confusing when using IntelliSense or using the classes in a visual designer.
These classes are all controls that are written to be compiled for either WPF or Silverlight 2.0. I know about ICustomTypeDescriptor and ICustomPropertyProvider, but I'm pretty certain those can't be used in Silverlight.
It's not as much a functional issue as a usability issue. What should I do?
Update
Some of the properties that I would really like to hide come from ancestors that are not my own and because of a specific tool I'm designing for, I can't do member hiding with the new operator. (I know, it's ridiculous)

Override them like Michael Suggests above and to prevent folks from using the overridden (sp?) methods, mark them as obsolete:
[Obsolete("These are not supported in this class.", true)]
public override void dontcallmeanymore()
{
}
If the second parm is set to true, a compiler error will be generated if anyone tries to call that method and the string in the first parm is the message. If parm2 is false only a compiler warning will be generated.

While you cannot prevent usage of those inherited members to my knowledge, you should be able to hide them from IntelliSense using the EditorBrowsableAttribute:
Using System.ComponentModel;
[EditorBrowsable(EditorBrowsableState.Never)]
private string MyHiddenString = "Muahahahahahahahaha";
Edit: Just saw this in the documentation comments, which makes it kinda useless for this purpose:
There is a prominent note that states that this attribute "does not suppress members from a class in the same assembly". That is true but not complete. Actually, the attribute does not suppress members from a class in the same solution.

One potential thing you can do is contain the object rather than extend from the other class. This will give you the most flexibility in terms of exposing what you want to expose, but if you absolutely need the object to be of that type it is not the ideal solution (however you could expose the object from a getter).
Thus:
public class MyClass : BaseClass
{
// Your stuff here
}
Becomes:
public class MyClass
{
private BaseClass baseClass;
public void ExposeThisMethod()
{
baseClass.ExposeThisMethod();
}
}
Or:
public class MyClass
{
private BaseClass baseClass;
public BaseClass BaseClass
{
get
{
return baseClass;
}
}
}

I think you're best least hackish way is to consider composition as opposed to inheritance.
Or, you could create an interface that has the members you want, have your derived class implement that interface, and program against the interface.

I know there's been several answers to this, and it's quite old now, but the simplest method to do this is just declare them as new private.
Consider an example I am currently working on, where I have an API that makes available every method in a 3rd party DLL. I have to take their methods, but I want to use a .Net property, instead of a "getThisValue" and "setThisValue" method. So, I build a second class, inherit the first, make a property that uses the get and set methods, and then override the original get and set methods as private. They're still available to anyone wanting to build something different on them, but if they just want to use the engine I'm building, then they'll be able to use properties instead of methods.
Using the double class method gets rid of any restrictions on being unable to use the new declaration to hide the members. You simply can't use override if the members are marked as virtual.
public class APIClass
{
private static const string DllName = "external.dll";
[DllImport(DllName)]
public extern unsafe uint external_setSomething(int x, uint y);
[DllImport(DllName)]
public extern unsafe uint external_getSomething(int x, uint* y);
public enum valueEnum
{
On = 0x01000000;
Off = 0x00000000;
OnWithOptions = 0x01010000;
OffWithOptions = 0x00010000;
}
}
public class APIUsageClass : APIClass
{
public int Identifier;
private APIClass m_internalInstance = new APIClass();
public valueEnum Something
{
get
{
unsafe
{
valueEnum y;
fixed (valueEnum* yPtr = &y)
{
m_internalInstance.external_getSomething(Identifier, yPtr);
}
return y;
}
}
set
{
m_internalInstance.external_setSomething(Identifier, value);
}
}
new private uint external_setSomething(int x, float y) { return 0; }
new private unsafe uint external_getSomething(int x, float* y) { return 0; }
}
Now valueEnum is available to both classes, but only the property is visible in the APIUsageClass class. The APIClass class is still available for people who want to extend the original API or use it in a different way, and the APIUsageClass is available for those who want something more simple.
Ultimately, what I'll be doing is making the APIClass internal, and only expose my inherited class.

To fully hide and mark not to use, including intellisense which I believe is what most readers expect
[Obsolete("Not applicable in this class.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

I tested all of the proposed solutions and they do not really hide new members.
But this one DOES:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new string MyHiddenProperty
{
get { return _myHiddenProperty; }
}
But in code-behide it's still accessible, so add as well Obsolete Attribute
[Obsolete("This property is not supported in this class", true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public new string MyHiddenProperty
{
get { return _myHiddenProperty; }
}

While clearly stated above that it is not possible in C# to change the access modifiers on inherited methods and properties, I overcame this issue through a sort of "fake inheritance" using implicit casting.
Example:
public class A
{
int var1;
int var2;
public A(int var1, int var2)
{
this.var1 = var1;
this.var2 = var2;
}
public void Method1(int i)
{
var1 = i;
}
public int Method2()
{
return var1+var2;
}
}
Now lets say you want a class B to inherit from class A, but want to change some accessibility or even change Method1 entirely
public class B
{
private A parent;
public B(int var1, int var2)
{
parent = new A(var1, var2);
}
int var1
{
get {return this.parent.var1;}
}
int var2
{
get {return this.parent.var2;}
set {this.parent.var2 = value;}
}
public Method1(int i)
{
this.parent.Method1(i*i);
}
private Method2()
{
this.parent.Method2();
}
public static implicit operator A(B b)
{
return b.parent;
}
}
By including the implicit cast at the end, it allows us to treat B objects as As when we need to. It can also be useful to define an implicit cast from A->B.
The biggest flaw to this approach is that you need to re-write every method/property that you intend to "inherit".
There's probably even more flaws to this approach, but I like to use it as a sort of "fake inheritance".
Note:
While this allows for changing the accessibility of public properties, it doesn't solve the issue of making protected properties public.

You can use an interface
public static void Main()
{
NoRemoveList<string> testList = ListFactory<string>.NewList();
testList.Add(" this is ok ");
// not ok
//testList.RemoveAt(0);
}
public interface NoRemoveList<T>
{
T this[int index] { get; }
int Count { get; }
void Add(T item);
}
public class ListFactory<T>
{
private class HiddenList: List<T>, NoRemoveList<T>
{
// no access outside
}
public static NoRemoveList<T> NewList()
{
return new HiddenList();
}
}

Related

C# Return a private type in protected function where private type will be accessible to all child classes

I have two classes, BaseO and PrivateO, defined in another class, Overflow. BaseO is a public class, and PrivateO is private. I also have a child class to BaseO, called ChildO, which is also public.
Now, in BaseO, I want to define a protected function protected Private0 getPrivate();, which ChildO1 can access. But this is not allowed, because getPrivate has a different accessibility than PrivateO.
I understand why this is a problem, if someone were to inherit BaseO from outside Overflow they would need to have access to PrivateO, which they don't.
I've gotten around the problem for now by using objects and casts, but I'd like to do it more correctly. Is there a way to specify that BaseO is not intended to be inherited from outside of Overflow?
internal is an idea, but I'd like this to work even when the code is not in a different assembly.
I have access to .NET 4.5 and C# 5, but any newer versions would also be interesting.
Example code:
public static class Overflow
{
private class PrivateO
{
public int foo;
}
public class BaseO
{
protected PrivateO GetPrivate() // inconsistent accessibility
{
return new PrivateO();
}
}
public class ChildO : BaseO
{
private int foo;
public ChildO()
{
this.foo = GetPrivate().foo; // <- desired behavior
}
}
}
Edit: Note that the example code is just that, an example. The real PrivateO class is a whole lot more complex, so it's not just a matter of retrieving an int. It also returns private builder classes and other non-trivial data structures.
Edit 2: Changed Overflow to a static class to emphasize that it in this case is used more as a namespace than as an instantiable class.
Provide an accessor property for the private/protected property:
class Overflow
{
private class PrivateO
{
public int foo;
}
public class BaseO
{
PrivateO privateO = new PrivateO();
public int PrivateFoo => privateO.foo;
}
public class ChildO : BaseO
{
private int foo;
public ChildO()
{
this.foo = PrivateFoo;
}
}
}
If Base0 never needs to be instantiated from the outside and all runtime types will be dervided ones like Child0 you can restrict inheritance to nested types:
public class BaseO
{
//private ctor avoids anyone extending this class
//outside Base0
private Base0 { }
PrivateO privateO = new PrivateO();
public int PrivateFoo => privateO.foo;
public class ChildO : BaseO
{
private int foo;
public ChildO()
{
this.foo = PrivateFoo;
}
}
}
Now you can:
var child0 = new Overflow.Base0.Child0();
But you can't do neither of the following outside Overflow:
class anotherChild0: Overflow.Base0 { }
var base0 = new Overflow.Base0(); //potentially problematic
If you actually need to allow var base0 = new Overflow.Base0(); outside Overflow then you are out of luck, you can't have it both ways; if someone can new up a Base0 and its not sealed, then he will be able to inherit from it.
In this case your best options are:
Live with allowing inheritance only inside the same assembly (internal constructor)
Do not expose Base0 and Child0 outside Overflow, expose an interface IBase0
Do a runtime check and zap any class calling Base0() from outside the assembly. YUCK! (I don't know why I'm even suggesting this).
You could make the class protected and embed it in BaseO:
class Overflow
{
public class BaseO
{
protected class PrivateO
{
public int foo;
}
protected PrivateO GetPrivate()
{
return new PrivateO();
}
}
public class ChildO : BaseO
{
private int foo;
public ChildO()
{
this.foo = GetPrivate().foo; // <- desired behavior
}
}
}
Is there a way to specify that BaseO is not intended to be inherited
from outside of Overflow?
I think that's what 'Sealed' is for.
When applied to a class, the sealed modifier prevents other classes
from inheriting from it.

Using class to describe data in C#

I'm writing an application in C#, which supports plugins. Each plugin has to introduce itself, such that application can prepare appropriate environment for it. The current info object looks more less like this:
class FilterInfo
{
public InputInfo[] inputs;
public OutputInfo[] outputs;
bool IsConfigurable;
bool IsPlayable;
string TypeName;
}
This structure will surely expand in future (however, I guess, that not much, it'll maybe double its size). I'm currently thinking on how to implement such info class properly.
In C++ I would do it the following way (I'll strip the class to one field to make the examples more readable):
class FilterInfo
{
private:
std::vector<const InputInfo> inputs;
public:
std::vector<const InputInfo> & GetInputs()
{
return inputs;
}
const std::vector<const InputInfo> & GetInputs() const
{
return inputs;
}
}
Now, the plugin would instantiate a FilterInfo class, fill-in its fields and then return const FilterInfo on request, such that noone may change contents of the info (well, noone should).
In C#, I can only imagine the following "safe" solution:
public interface IInputInfo
{
bool SomeData
{
get;
}
}
public class InputInfo : IInputInfo
{
private bool someData;
public bool SomeData
{
get
{
return someData;
}
set
{
someData = value;
}
}
public bool IInputInfo.SomeData
{
get
{
return someData;
}
}
}
public interface IFilterInfo
{
ReadOnlyCollection<IInputInfo> Inputs
{
get;
}
}
public class FilterInfo : IFilterInfo
{
private InputInfo[] inputs;
public InputInfo[] Inputs
{
get
{
return inputs;
}
set
{
inputs = value;
}
}
public ReadOnlyCollection<IInputInfo> IFilterInfo.Inputs
{
return inputs;
}
}
The plugin will, of course, return IFilterInfo instead of FilterInfo, such that the data is readonly (OK, I know about reflection, the matter is to notify the user, that the data should not be changed). However, this solution looks very clumsy to me - especially when compared to compact version I cited earlier.
Another solution may to be create FilterInfo only with getters, but it would require passing the data into it in some way and probably would end up with a huge constructor with lots of parameters.
Edit: Another solution is to create a struct and return its copy during every request. However, arrays are copied by reference, so I would have to copy them manually each time.
Yet another one is to construct the FilterInfo from the scratch each time anyone requests it, eg.
public FilterInfo Info
{
get
{
return new FilterInfo()
{
IsConfigurable = true,
IsPlayable = false,
Inputs = new[]
{
new InputInfo()
{
// (...)
}
}
}
}
}
Is there an elegant way to solve this problem?
I think you got it almost right the first time:
Define a public IFilterInfo interface in the pluggable assembly that only allows reading.
Implement the interface in a FilterInfo class in the plugin assembly that has internal setters on its properties.
Have a method return a new instance of the FilterInfo class upon request. Convention suggests to use a method instead of a property in cases where a new instance is constructed each time. (If you insist on using a property you could store the instance once it has been constructed and return it through the property)
Example:
In the pluggable assembly:
public interface IFilterInfo {
bool IsPlayable { get; }
bool IsConfigurable { get; }
}
In the plugin assembly:
internal class FilterInfo : IFilterInfo {
public bool IsPlayable { get; internal set; }
public bool IsConfigurable { get; internal set; }
}
public IFilterInfo GetFilterInfo() {
return new FilterInfo() { IsPlayable = true, IsConfigurable = false };
}
Internal setters and a read-only interface should be enough to ensure that the properties aren't modified outside the plugin assembly.
What about setting the setters to private or protected.
public class FilterInfo
{
public InputInfo[] inputs { get; private set; }
public OutputInfo[] outputs { get; private set; };
bool IsConfigurable;
bool IsPlayable;
string TypeName;
public void SetInputs(...)
{
InputInfo[] allInputs;
//do stuff
inputs = AllInput;
}
public void SetOutputs(...)
{
OutputInfo[] allOutputs;
//do stuff
outputs = AllOutput;
}
}
You would be able to have internal methods to set the data or go protected and allow modifying the objects through inheritance.
UPDATE
What about using the internal accessor for the setter. This way nothing will be able to access the setter unless it is declared in the InternalsVisibleTo assembly level attribute, which would be defined in the assembly containing FilterInfo.
The following post gives a good explanation on how to do this using the internal keyword.
Internal Description
UPDATE
Another solution may to be create FilterInfo only with getters, but it would require passing the data into it in some way and probably would end up with a huge constructor with lots of parameters.
According to this the only issue with not having a getter is that you still need to pass in data. The original solution allows this to happen. I guess I might be a little confused. If the plugin is able to change the information in this API which is by reference I am guessing. Then if the application is referencing the same assembly, it too would have the same accessors provided to the plugin. It seems that short of setting the setters to internal and allowing access through attributes would be the only way to achieve that type of functionality. But that wont work in your case because you do not know the assemblies that are referencing your API.
I don't quite sure about what you really want, but it seems the builder pattern is good for this case.
First, the setter or constructor can be marked internal, means that only the assembly can access the constructor or setter. Leave the getter public, it is needed, isn't it?
Then your builder class (assume you are using the constructor injection):
public class FilterInfoBuilder{
public FilterInfoBuilder(InputInfo[] inputInfo){
this.inputInfo = inputInfo;
}
private InputInfo[] inputInfo;
public FilterInfo Create(){
FilterInfo filterInfo = new FilterInfo(inputInfo);
return filterInfo;
}
}
Maybe I misunderstand your requirement though.
EDIT
You can tweak the builder as a dynamic setter though. Now consider using internal setter instead of internal constructor.
public class FilterInfoBuilder{
public FilterInfoBuilder(InputInfo[] inputInfo){
filterInfo = new FilterInfo();
filterInfo.InputInfo = inputInfo;
}
private FilterInfo filterInfo;
public FilterInfo FilterInfo{
get{
return filterInfo;
}
}
public void ChangeInputInfo(InputInfo[] inputInfo){
filterInfo.InputInfo = inputInfo;
}
}
You can use FilterInfoBuilder.FilterInfo to access the FilterInfo class. To modify it, you can create internal methods inside the builder class.
I don't really sure about the solution though, as I haven't found the design in any documented source.
More EDIT
I have another design, only if you can separate the interface between assemblies and make sure the application access the interface and not the class.
example:
public interface IInputInfoSetable{
public InputInfo[] InputInfo{
set;
}
}
public interface IFilterInfo{
public InputInfo[] InputInfo{
get;
}
}
public class FilterInfo: IFilterInfo, IInputInfoSetable{
// implement explicitly both of the interface.
}

C# Pass a Class as a parameter

I have an Interface, that has some methods
interface IFunction
{
public double y(double x);
public double yDerivative(double x);
}
and I've got static classes, that are implementing it.
static class TemplateFunction:IFunction
{
public static double y(double x)
{
return 0;
}
public static double yDerivative(double x)
{
return 0;
}
}
I want to pass this classes as a parameter to another function.
AnotherClass.callSomeFunction(TemplateFunction);
And some other class that catches the request
class AnotherClass
{
IFunction function;
public void callSomeFunction(IFunction function)
{
this.fuction = function;
}
}
Well, it doesn't work... I've tried to use the Type expression, but that seams to break the idea of using an interface. Does anyone have an idea, how to correct the code?
Static classes can't implement interfaces, but you can easily overcome this by making your class non static and a generic method:
class AnotherClass
{
IFunction function;
public void callSomeFunction<T>()
where T: IFunction, new()
{
this.fuction = new T();
}
}
This is much close to the syntax you wanted:
AnotherClass.callSomeFunction<TemplateFunction>();
But I actually think that this way is too complicated and likely to confuse someone, you should follow Servy's approach which is way simpler:
AnotherClass.callSomeFunction(TemplateFunction.Instance);
The conceptual way of getting a static class to implement an interface is to use a singleton, even if that singleton contains no state:
public sealed class TemplateFunction : IFunction
{
private TemplateFunction() { }
private static TemplateFunction instance = new TemplateFunction();
public static TemplateFunction Instance { get { return instance; } }
public double y(double x)
{
return 0;
}
public double yDerivative(double x)
{
return 0;
}
}
Another option is to just not use an interface, and instead have your method accept one or more delegates. It's fine if you only need a single method, if you have two it can sometimes be okay, and sometimes not. If you have more than two, it's usually a problem.
public class AnotherClass
{
public static void callSomeFunction(Func<double, double> y
, Func<double, double> yDerivitive)
{
//store delegates for later use
}
}
AnotherClass.callSomeFunction(TemplateFunction.y, TemplateFunction.yDerivative);
How about you use a generic method to catch the type that you are calling for.
Like this:
public void callSomeFunction<T>()
{
//the type is T
//you can create an instance of T with System.Activator.CreateInstance(T) and T's methods
//alternatively if the classes are static you can call the methods with reflection knowing only their name.
}
And anyway, if the reason you want to do this is because you want to have multiple classes that implement the same methods and you want to write a method that will call a certain implementation of those methods based on type, then other solutions might be in order, like overloading.
Or if indeed this is what you want to do, then keep in mind that passing an interface won't allow you to use the approach i presented you with, because the Activator needs to have access to the Type so that it can create an instance.
You can do as Allon said and change the TemplateFunction to none static and then do this:
var anotherClass = new AnotherClass();
var templateFunction = new TemplateFunction();
anotherClass.callSomeFunction(templateFunction);

How can I access a static property of type T in a generic class?

I am trying to accomplish the following scenario that the generic TestClassWrapper will be able to access static properties of classes it is made of (they will all derive from TestClass). Something like:
public class TestClass
{
public static int x = 5;
}
public class TestClassWrapper<T> where T : TestClass
{
public int test()
{
return T.x;
}
}
Gives the error:
'T' is a 'type parameter', which is not valid in the given context.
Any suggestions?
You can't, basically, at least not without reflection.
One option is to put a delegate in your constructor so that whoever creates an instance can specify how to get at it:
var wrapper = new TestClassWrapper<TestClass>(() => TestClass.x);
You could do it with reflection if necessary:
public class TestClassWrapper<T> where T : TestClass
{
private static readonly FieldInfo field = typeof(T).GetField("x");
public int test()
{
return (int) field.GetValue(null);
}
}
(Add appropriate binding flags if necessary.)
This isn't great, but at least you only need to look up the field once...
Surely you can just write this:
public int test()
{
return TestClass.x;
}
Even in a nontrivial example, you can't override a static field so will always call it from your known base class.
Why not just return TestClass.x?
Generics do not support anything related to static members, so that won't work. My advice would be: don't make it static. Assuming the field genuinely relates to the specific T, you could also use reflection:
return (int) typeof(T).GetField("x").GetValue(null);
but I don't recommend it.
Another solution is to simply not make it static, and work with the new() constraint on T to instantiate the object. Then you can work with an interface, and the wrapper can get the property out of any class that implements that interface:
public interface XExposer
{
Int32 X { get; }
}
public class TestClass : XExposer
{
public Int32 X { get { return 5;} }
}
public class XExposerWrapper<T> where T : XExposer, new()
{
public Int32 X
{
get { return new T().X; }
}
}
In fact, you can change that to public static Int32 X on the TestClassWrapper and simply get it out as Int32 fetchedX = XExposerWrapper<TestClass>.X;
Though since whatever code calls this will have to give the parameter T those same constraints, the wrapper class is pretty unnecessary at this point, since that calling code itself could also just execute new T().X and not bother with the wrapper.
Still, there are some interesting inheritance models where this kind of structure is useful. For example, an abstract class SuperClass<T> where T : SuperClass<T>, new() can both instantiate and return type T in its static functions, effectively allowing you to make inheritable static functions that adapt to the child classes (which would then need to be defined as class ChildClass : SuperClass<ChildClass>). By defining protected abstract functions / properties on the superclass, you can make functions that apply the same logic on any inherited object, but customized to that subclass according to its implementations of these abstracts. I use this for database classes where the table name and fetch query are implemented by the child class. Since the properties are protected, they are never exposed, either.
For example, on database classes, where the actual fetching logic is put in one central abstract class:
public abstract class DbClass<T> where T : DbClass<T>, new()
{
protected abstract String FetchQuery { get; }
protected abstract void Initialize(DatabaseRecord row);
public static T FetchObject(DatabaseSession dbSession, Int32 key)
{
T obj = new T();
DatabaseRecord record = dbSession.RetrieveRecord(obj.FetchQuery, key);
obj.Initialize(record);
return obj;
}
}
And the implementation:
public class User : DbClass<User>
{
public Int32 Key { get; private set;}
public String FirstName { get; set;}
public String LastName { get; set;}
protected override String FetchQuery
{ get { return "SELECT * FROM USER WHERE KEY = {0}";} }
protected override void Initialize(DatabaseRecord row)
{
this.Key = DbTools.SafeGetInt(row.GetField("KEY"));
this.FirstName = DbTools.SafeGetString(row.GetField("FIRST_NAME"));
this.LastName = DbTools.SafeGetString(row.GetField("LAST_NAME"));
}
}
This can be used as:
User usr = User.FetchObject(dbSession, userKey);
This is a rather simplified example, but as you see, this system allows a static function from the parent class to be called on the child class, to return an object of the child class.
T is a type, not parameter or variable so you cannot pick any value from any members. Here is a sample code.
public class UrlRecordService
{
public virtual void SaveSlug<T>(T entity) where T : ISlugSupport
{
if (entity == null)
throw new ArgumentNullException("entity");
int entityId = entity.Id;
string entityName = typeof(T).Name;
}
}
public interface ISlugSupport
{
int Id { get; set; }
}
cjk and Haris Hasan have the most-correct answers to the question as asked. However in this comment the OP implies that he is after something else not quite possible in C#: a way to define a contract for a static member in a derived class.
There isn't a way to strictly define this, but it is possible to set up a pattern that may be implied by a base class (or interface); e.g.:
public class TestClass
{
private static int x;
public virtual int StaticX => x;
}
or if not intended to be used directly
public abstract class AbstractTestClass
{
public abstract int StaticX {get;}
}
or (my preference in this contrived example)
public interface ITest
{
int StaticX {get;}
}
Elsewhere, this pattern of a StaticXxx member may be (loosely) associated with implementations that should back the member with static fields (as in TestClass above).
What's kind of fun is that this can be (re)exposed as static by the generic wrapper, because generic statics are isolated to each type used.
public class TestClassWrapper<T> where T : ITest, new()
{
private readonly static T testInstance = new T();
public static int test() => testInstance.x;
}
This uses a new() condition, but an associated static, generic factory pattern for creating ITest (or TestClass or AbstractTestClass) instances may also be used.
However this may not be feasible if you can't have long-lived instances of the class.
In this situation you assume that T is a subclass of TestClass. Subclasses of TestClass will not have the static int x.

C# splitting property get and set between classes. Why doesn't it work?

I'm trying to provide two classes to my users - one that is read-only and one that is writable. The r/o will only have getters, while the writable will inherit from it and add the setters.
I was under the impression that C# should be able to handle it, but the compiler disagreed.
Why doesn't this work? Any workarounds?
class A
{
protected int m_val;
public int Val
{
get { return m_val; }
}
}
class B : A
{
public int Val
{
set { m_val = value; }
}
}
class Test
{
static void Main(string[] args)
{
B b = new B();
b.Val++; // <-- WHY DOESN'T THIS WORK?!
}
}
P.S. the protected variable in the example above is artificial. My class actually wraps some native resources and the getting/setting happens on either const or mutable native pointer.
partial applies to a single type - not 2 types (A and B). You would need something more like below, ideally keeping the field private:
class A
{
private int m_val;
public int Val
{
get { return m_val; }
protected set { m_val = value; }
}
}
class B : A
{
public new int Val
{
get { return base.Val;}
set { base.Val = value; }
}
}
I'm not sure about why you need this, but a possibly better design would be to have two interfaces rather than two classes, and a single class that implements both. Then you could hand your client code whichever interface you'd like them to use, with the added bonus of being able to use the values set on a writable interface and hand it over to someone else as a read-only interface.
Mark the setters as protected in the parent, and expose public setters in the child.

Categories