In C++, you can pass into a function an object that is const. This forces the code to treat that object as ‘read only’ (ignoring the fact that you can strip constness away using casts). I’m trying to do the same with C#. I have an interface that the user will implement. One of the methods will be given an object as a parameter. How do I make the object ‘const’ in the scope of the method and mutable otherwise.
Solution: interfaces. I make an interface where the only action available on a property, is ‘get’.
public interface IVal { ... }
public interface IFoo
{
IVal Val { get; }
}
public class Foo : IFoo
{
public IVal Val { get; }
}
I pass by interface and everything is amazing. However, in my concrete class, I would like to have a ‘set’ available. It would allow me to set a concrete class Value. How would my concrete class look like?
I was thinking of using the ‘internal’ keyword. I read that it exposes the method/property to code within your own assembly. Is this my answer?
EDIT: To illustrate this better, I added a setter that would automatically cast for me. However, for each property, this is a lot of repetative code:
private Val _val;
public IVal Val
{
get { return this._val; }
set { this._val = value as Val; }
}
You can just add the
setand it will work fine:Like this, you can set the value if you have
Foo, but not if you haveIFoo. Similar to the C++ case, if you haveIFoo, you can cast toFoo(as long as the object actually isFoo) and then use the setter.Another option is to make the setter
protectedorprivate:This allows you to make sure that only code in this class (or inherited classed in the case of
protected) can set the property.Regarding
internal: yes, it exposes the member only to code in the same assembly (and friend assemblies). But this is not used very often. What is used (and useful) are internal types, which is even the default, if you don’t specify that that class ispublic.This could help you with your problem. If you make
Foointernal, a method in other assembly that hasIFoowon’t be able to set the property, even with casting.Of course, the code could always use reflection to set the property. But you shouldn’t worry about that most of the time.