Const parameter to function

  • Thread starter Thread starter awheeler
  • Start date Start date
A

awheeler

Is it possible to pass an object reference to a function and ensure
that the function is unable to modify the state of the object?

Thanks.
 
Assuming you mean the object itself, and not the reference (reassigning);
unless the object is immutable [trivial case], then no; you could pass a
clone, or perhaps use the memento pattern?

Marc
 
Is it possible to pass an object reference to a function and ensure
that the function is unable to modify the state of the object?

One clever alternative that was mentioned recently in another thread is
to create an interface for whatever of the object's properties / events
/ methods are required, but not include any setters in the interface
(or any methods that modify the object's state). For example:

public interface IImmutablePerson
{
int Id { get; }
string Name { get; }
}

public class Person : IImmutablePerson
{
private int _id;
private string _name;

public Person(int id, string name) { this._id = id; this._name =
name; }
public int Id { get { return this._id; } set { this._id = value; }
}
public string Name ( get { return this._name; } set { this._name =
value; } }
public void TrimName() { this._name = this._name.Trim(); }
}

public void DoSomethingWithPerson(IImmutablePerson person) { ... }

In this case, you're not _guaranteed_, but are reasonably assured that
DoSomethingWithPerson will not change anything in the Person object,
because it uses it via the interface IImmutablePerson, which doesn't
declare any property setters and doesn't include the method TrimName()
(which modifies the Name).

Now, if DoSomethingWIthPerson chose to be evil, it could always do
this:

Person mutablePerson = (Person)person;
mutablePerson.Name = "foo";

but this would clearly violate the intent of the declaration, which is
that the argument not be modified in any way.

If you truly, truly want pass-by-value at the object state level, with
full guarantees, I would say Clone that puppy, and pass the clone.
(This assumes, of course, that the object in question implements
ICloneable. Even then, the method might be able to modify objects that
are referred to by both the original object and the clone, if there are
any.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top