How to implement immutable types efficiently

When coding C #, I often find that I implement immutable types. I always end up writing quite a lot of code, and I wonder if there is a faster way to achieve it.

What I usually write:

public struct MyType
{
  private Int32 _value;
  public Int32 Value { get { return _value;} }

  public MyType(Int32 val)
  {
     _value = val;
  }
}

MyType alpha = new MyType(42);

This becomes quite complicated when the number of fields grows and gets a lot. Is there a more efficient way to do this?

+5
source share
3 answers

The only way to offer less code is to use something like ReSharper to automatically generate code for you. If you start with something like:

public class MyType
{
    private int _value;
}

you can generate read-only properties to give:

public class MyType
{
    private int _value;
    public int Value{get {return _value;}}
}

followed by a constructor to give:

public class MyType
{
    private int _value;
    public int Value{get {return _value;}}

    public MyType(int value)
    {
        _value = value;
    }
}

- 8 .


, :

public sealed class MyType
{
    public int Value{get {return _value;}}
    private readonly int _value;

    public MyType(int value)
    {
        _value = value;
    }
}

( , ) _value, . , ReSharper , ( ) .

+5

, :

public struct MyType
{  
  public Int32 Value { get; private set; }

  public MyType(Int32 val)
  {
     Value = val;
  }
}
+4

! xml "immutable.snippet", Visual Studio, "", " " . ! "immutable" TAB, .

@adrianbanks.

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>Immutable type (C#)</Title>
      <Author>Alfonso Cora</Author>
      <Description>Creates an immutable type</Description>
      <HelpUrl>http://stackoverflow.com/questions/7236977/how-to-efficiently-implement-immutable-types</HelpUrl>
      <Shortcut>immutable</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="true">
          <ID>type</ID>
          <ToolTip>The type on which this immutable type is based.</ToolTip>
          <Default>int</Default>
          <Function>
          </Function>
        </Literal>
        <Literal Editable="true">
          <ID>class</ID>
          <ToolTip>The name of the immutable type.</ToolTip>
          <Default>MyImmutableType</Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[public sealed class $class$
{
    public $type$ Value{get {return _value;}}
    private readonly $type$ _value;

    public $class$($type$ value)
    {
        _value = value;
    }
}]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>
+1

All Articles