If the class of the object you're passing was written by you, then you're in luck.
Ask yourself: if C# had a const
feature, what operations on the object would I expect to be banned through a const
reference to my class?
Then define an interface
that leaves out the banned operations.
For example:
class MyClass
{
public string GetSomething() { ... }
public void Clobber() { ... }
public int Thing { get { ... } set { ... } }
}
The corresponding "const" interface might be:
interface IConstMyClass
{
public string GetSomething() { ... }
public int Thing { get { ... } }
}
Now amend the class:
class MyClass : IConstMyClass
{
Now you can use IConstMyClass
to mean const MyClass
.
void MyMethod(int x, int y, IConstMyClass obj)
Note: there will be those who will tell you that this isn't enough. What if MyMethod
casts back to MyClass
? But ignore them. Ultimately the implementor can use reflection to get around any aspect of the type system - see this amusing example.
The only option to stop reflection attacks is the trivial approach: make a totally disconnected clone.