Coming from a c++ background, I'm used to sticking the const keyword into function definitions to make the object being passed in a read-only value. However, this is not possible in C#, as I found out (please correct me if I'm wrong). So, after some googling, I came to the conclusion that the only way to make a read only object is to write an interface that only has 'get' properties and pass that in instead. Elegant, I must say.
public interface IFoo
{
IMyValInterface MyVal{ get; }
}
public class Foo : IFoo
{
private ConcreteMyVal _myVal;
public IMyValInterface MyVal
{
get { return _myVal; }
}
}
I would pass it into:
public void SomeFunction(IFoo fooVar)
{
// Cannot modify fooVar, Excellent!!
}
This is fine, however, in the rest of my code, I would like to modify my object normally. If I add a 'set' property to the interface, this will break my readonly restriction. I can add a 'set' property to Foo (and not IFoo), but the signature expects an interface rather than a Concrete object. I would have to do some casting.
// Add this to class Foo. Might assign null if cast fails??
set { _myVal = value as ConcreteMyVal; }
// Somewhere else in the code...
IFoo myFoo = new Foo;
(myFoo as Foo).MyFoo = new ConcreteMyVal();
Is there a more elegant way of making 'const' or readonly function parameters without adding another property or a function??