Lock object to prevent any data changes

A bit of this odd ...

Suppose I have the following class:

public class Wibble
{
  public string Foo {get;set;}
  public string Bar {get;set;}
}

This class is used in the process when the values ​​of Foo and Bar are updated or changed. However, after a certain point in the process, I want to “block” the instance to prevent any changes. So the question is, what is the best way to do this?

The kind solution will look something like this:

public class Wibble
{
  private string _foo;
  private string _bar;

  public bool Locked {get; set;}

  public string Foo
  {
    get
    {
      return this._foo
    }
    set
    {
        if (this.Locked)
        {
          throw new ObjectIsLockedException()
        }

        this._foo = value;
    }
  }

  public string Bar
  {
    get
    {
      return this._bar
    }
    set
    {
        if (this.Locked)
        {
          throw new ObjectIsLockedException()
        }

        this._bar = value;
    }
  }
}

However, this seems a little inelegant.

, , , . Wibble , , . , , . "" , , .

+3
4

- , , , , , " ". , , .

, , . , "Builder", . StringBuilder String. , , , -, , . , , Builder .

+2

:

:

public class Wibble
{
  public string Foo { get; private set; }
  public string Bar { get; private set; }

  public Wibble(string foo, string bar)
  {
    this.Foo = foo;
    this.Bar = bar
  } 
}

, , , .

public class MutableWibble 
{
  public string Foo { get; set; }
  public string Bar { get; set; }

  public Wibble CreateImmutableWibble() 
  {
    return new Wibble(this.Foo, this.Bar);
  }
}

#, .

: http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.71%29.aspx

+1

Another option you have is to use BinaryFormatter to create a phased cloning of the object that will be "locked". Although you are not blocking the object you are creating a snapshot that you can discard, while the original remains unchanged.

0
source

All Articles