Sergei Churbanov
Sergei Churbanov

Reputation: 5

Method that creates new object of the same type, replaces initial object with the new one

i know that .NET String class uses such behaviour, but I can't find any implementation, and i don't know how to name this behaviour. Any ideas will be helpful.

Upvotes: 0

Views: 83

Answers (1)

Erik Philips
Erik Philips

Reputation: 54618

The string class is referred to as being Immutable.

An extremely simplified example might look like:

public sealed class MyValue
{
  public MyValue(int value)
  {
    this.Value = value;
  } 

  public int Value { get; private set }

  public MyValue Add(int value)
  {
    return new MyValue(this.Value + value);
  }
}

The object in this context cannot be changed. If you require another MyValue object with the current value added to another value, you get a new object.

Upvotes: 3

Related Questions