{"action":"created","issue":{"url":"https://api.github.com/repos/dotnet/roslyn/issues/159","labels_url":"https://api.github.com/repos/dotnet/roslyn/issues/159/labels{/name}","comments_url":"https://api.github.com/repos/dotnet/roslyn/issues/159/comments","events_url":"https://api.github.com/repos/dotnet/roslyn/issues/159/events","html_url":"https://github.com/dotnet/roslyn/issues/159","id":55916655,"number":159,"title":"Proposal: Immutable Types","user":{"login":"stephentoub","id":2642209,"avatar_url":"https://avatars.githubusercontent.com/u/2642209?v=3","gravatar_id":"","url":"https://api.github.com/users/stephentoub","html_url":"https://github.com/stephentoub","followers_url":"https://api.github.com/users/stephentoub/followers","following_url":"https://api.github.com/users/stephentoub/following{/other_user}","gists_url":"https://api.github.com/users/stephentoub/gists{/gist_id}","starred_url":"https://api.github.com/users/stephentoub/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/stephentoub/subscriptions","organizations_url":"https://api.github.com/users/stephentoub/orgs","repos_url":"https://api.github.com/users/stephentoub/repos","events_url":"https://api.github.com/users/stephentoub/events{/privacy}","received_events_url":"https://api.github.com/users/stephentoub/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/dotnet/roslyn/labels/1%20-%20Planning","name":"1 - Planning","color":"cccccc"},{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Area-Language%20Design","name":"Area-Language Design","color":"5319e7"},{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Feature%20Request","name":"Feature Request","color":"fc2929"},{"url":"https://api.github.com/repos/dotnet/roslyn/labels/Language-C%23","name":"Language-C#","color":"207de5"}],"state":"open","locked":false,"assignee":{"login":"MadsTorgersen","id":6677272,"avatar_url":"https://avatars.githubusercontent.com/u/6677272?v=3","gravatar_id":"","url":"https://api.github.com/users/MadsTorgersen","html_url":"https://github.com/MadsTorgersen","followers_url":"https://api.github.com/users/MadsTorgersen/followers","following_url":"https://api.github.com/users/MadsTorgersen/following{/other_user}","gists_url":"https://api.github.com/users/MadsTorgersen/gists{/gist_id}","starred_url":"https://api.github.com/users/MadsTorgersen/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/MadsTorgersen/subscriptions","organizations_url":"https://api.github.com/users/MadsTorgersen/orgs","repos_url":"https://api.github.com/users/MadsTorgersen/repos","events_url":"https://api.github.com/users/MadsTorgersen/events{/privacy}","received_events_url":"https://api.github.com/users/MadsTorgersen/received_events","type":"User","site_admin":false},"milestone":null,"comments":31,"created_at":"2015-01-29T15:53:44Z","updated_at":"2015-02-05T19:53:34Z","closed_at":null,"body":"## Problem\r\nOne of the uses of 'readonly' fields is in defining immutable types, types that once constructed cannot be visibly changed in any way.  Such types often require significant diligence to implement, both from the developer and from code reviewers, because beyond 'readonly' there’s little assistance provided by the compiler in ensuring that a type is actually immutable.  Additionally, there’s no way in the language (other than in type naming) for a developer to convey that a type was meant to be immutable, which can significantly impact how it’s consumed, e.g. whether a developer can freely share an instance of the type between multiple threads without concern for race conditions.\r\n\r\nConsider this type:\r\n```C#\r\npublic class Person\r\n{\r\n    public Person(string firstName, string lastName, DateTimeOffset birthDay)\r\n    {\r\n        FirstName = firstName;\r\n        LastName = lastName;\r\n        BirthDay = birthDay;\r\n    }\r\n\r\n    public string FirstName { get; }\r\n    public string LastName { get; }\r\n    public DateTime BirthDay { get; }\r\n\r\n    public string FullName => $\"{FirstName} {LastName}\";\r\n    public TimeSpan Age => DateTime.UtcNow – BirthDay;\r\n}\r\n```\r\n\r\nWriting this type requires relatively minimal boilerplate.  It also happens to be immutable: there are no exposed fields, there are no setters on any properties (the get-only auto-props will be backed by 'readonly' fields), all of the fields are of immutable types, etc.  However, there is no way for the developer to actually express the intent to the compiler that an immutable type was desired here and thus get compiler checking to enforce this.  At some point in the future, a developer could add a setter not realizing this type was meant to be immutable, and all of a sudden consumers of this type that were expecting full immutability (e.g. they'd avoiding making defensive copies) will now be very surprised:\r\n\r\n```C#\r\npublic class Person\r\n{\r\n    public Person(string firstName, string lastName, DateTimeOffset birthDay)\r\n    {\r\n        FirstName = firstName;\r\n        LastName = lastName;\r\n        BirthDay = birthDay;\r\n    }\r\n\r\n    public string FirstName { get; }\r\n    public string LastName { get; }\r\n    public DateTime BirthDay { get; set; } // Oops!\r\n\r\n    public string FullName => $\"{FirstName} {LastName}\";\r\n    public TimeSpan Age => DateTime.UtcNow – BirthDay;\r\n}\r\n```\r\n\r\nSimilarly, the class could be augmented with an additional 'readonly' property but of a non-immutable type:\r\n\r\n```C#\r\npublic class Person\r\n{\r\n    public Person(string firstName, string lastName, DateTimeOffset birthDay, Person[] ancestors)\r\n    {\r\n        FirstName = firstName;\r\n        LastName = lastName;\r\n        BirthDay = birthDay;\r\n        Ancestors = ancestors;\r\n    }\r\n\r\n    public string FirstName { get; }\r\n    public string LastName { get; }\r\n    public DateTime BirthDay { get; }\r\n    public Person[] Ancestors { get; }; // Oops!\r\n\r\n    public string FullName => $\"{FirstName} {LastName}\";\r\n    public TimeSpan Age => DateTime.UtcNow – BirthDay;\r\n}\r\n```\r\n\r\nAnd so on.  The developer has tried to design an immutable type, but without a way to declare that fact, and without compiler verification of that declaration, it is easy for bugs to slip in.\r\n\r\n## Solution: Immutable Types\r\nWe can introduce the notion of immutable types to C#.  A type, either a class or a struct, can be annotated as \"immutable\":\r\n\r\n```C#\r\npublic immutable class Person\r\n{\r\n    public Person(string firstName, string lastName, DateTimeOffset birthDay)\r\n    {\r\n        FirstName = firstName;\r\n        LastName = lastName;\r\n        BirthDay = birthDay; \r\n    }\r\n\r\n    public string FirstName { get; }\r\n    public string LastName { get; }\r\n    public DateTime BirthDay { get; }\r\n\r\n    public string FullName => $\"{FirstName} {LastName}\";\r\n    public TimeSpan Age => DateTime.UtcNow – BirthDay;\r\n}\r\n```\r\n\r\nWhen such an annotation is applied, the compiler validates that the type is indeed immutable.  All fields are made implicitly readonly (though it’s ok for a developer to explicitly state the ‘readonly’ keyword if desired) and be of immutable types (all of the core types like Int32, Double, TimeSpan, String, and so on in the .NET Framework would be annotated as immutable).  Additionally, the constructor of the type would be restricted in what it can do with the 'this' reference, limited only to directly reading and writing fields on the instance, e.g. it can’t call methods on 'this' (which could read the state of the immutable object before it was fully constructed and thus later perceive the immutable type as having changed), and it can’t pass 'this' out to other code (which could similar perceive the object changing).  This includes being prohibited from capturing 'this' into an anonymous method in the ctor. A type being 'immutable' doesn't mean that its operations are pure, just that the state within the object can't observably change; an immutable type would still be able to access statics, could still mutate mutable objects passed into its methods, etc.\r\n\r\nThe 'immutable' keyword would also work as an annotation on generic types.\r\n\r\n```C#\r\npublic immutable struct Tuple<T1, T2>\r\n{\r\n    public Tuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }\r\n    public T1 Item1; // Implicitly readonly\r\n    public T2 Item2; // Implicitly readonly\r\n}\r\n```\r\n\r\nApplying 'immutable' to a type with generic parameters would enforce all of the aforementioned rules, except that the generic type parameters wouldn't be enforced to be immutable: after all, without constraints on the generic type parameters, there’d be no way for the implementation of the open generic to validate that the type parameters are immutable.  As such, a generic type annotated as 'immutable' can be used to create both mutable and immutable instances: a generic instantiation is only considered to be immutable if it’s constructed with known immutable types:\r\n\r\n```C#\r\nvoid Usage<U>()\r\n{\r\n    Tuple<string, string>         local1; // considered immutable\r\n    Tuple<int, string>            local2; // considered immutable\r\n    Tuple<int, IC>                local3; // considered immutable\r\n    Tupe<Tuple<int, string>, int> local4; // considered immutable\r\n    Tuple<string, U>              local5; // considered mutable\r\n    Tuple<C, C>                   local6; // considered mutable\r\n    Tuple<Tuple<int, C>, int>     local6; // considered mutable\r\n}\r\nimmutable class IC { }\r\nclass C { }\r\n```\r\n\r\nSuch concrete instantiations could be used as fields of other immutable types _iff_ they're immutable.  But whether a generic instantiation is considered to be immutable or not has other effects on consumers of the type, for example being able to know that an instance is immutable and thus can be shared between threads freely without concern for race conditions.  As such, the IDE should do the leg work for the developer and highlight whether a given generic instantiation is considered to be immutable or mutable (or unknown, in the case of open generics).  \r\n\r\nHowever, the immutability question also affects other places where the compiler needs to confirm that a type is in fact immutable.  One such place would be with a new immutable generic constraint added to the language (there are conceivably additional places in the future that the language could depend on the immutability of a type).  Consider this variation on the tuple type previously shown:\r\n\r\n```C#\r\npublic immutable struct ImmutableTuple<T1, T2>(T1 item1, T2 item2) \r\n    where T1 : immutable\r\n    where T2 : immutable\r\n{\r\n    public ImmutableTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; }\r\n    public T1 Item1;\r\n    public T2 Item2;\r\n}\r\n```\r\n\r\nThe only difference from the previous version (other than a name change for clarity) is that we’ve constrained both generic type parameters to be 'immutable'.  With that, the compiler would enforce that all types used in generic instantiations of this type are 'immutable' and satisfy all of the aforementioned constraints.\r\n\r\n```C#\r\nvoid Usage<U>()\r\n{\r\n    ImmutableTuple<string, string>         local1; // Ok\r\n    ImmutableTuple<int, string>            local2; // Ok\r\n    ImmutableTuple<int, IC>                local3; // Ok\r\n    ImmutableTupe<Tuple<int, string>, int> local4; // Ok\r\n    ImmutableTuple<string, U>              local5; // Error: ‘U’ is not immutable\r\n    ImmutableTuple<C, C>                   local6; // Error: ‘C’ is not immutable\r\n    ImmutableTuple<Tuple<int, C>, int>     local6; // Error: ‘Tuple<int,C>’ is not immutable\r\n}\r\nimmutable class IC { }\r\nclass C { }\r\n```\r\n\r\nWith such constraints, it’s possible to create deeply immutable types, both non-generic and generic, and to have the compiler help fully validate the immutability.\r\n\r\nHowever, there are times when you may want to cheat, where you want to be able to use the type to satisfy immutable constraints, and potentially have some of the type’s implementation checked for the rules of immutability, but where you need to break the rules in the implementation in a way that’s still observably immutable but not physically so. For example, consider building an ImmutableArray type that wraps an underlying array.  As arrays are themselves mutable (code can freely write to an array’s elements), it’s not normally possible to store an array as a field of an immutable type:\r\n\r\n```C#\r\npublic immutable class ImmutableArray<T>\r\n{\r\n    readonly T[] m_array; // Error: The types of fields in immutable types must be immutable\r\n    …\r\n}\r\n```\r\n\r\nTo work around this, we can resort to unsafe code.  Marking an immutable type as 'unsafe' would disable the rule checking for immutability in the entire type and put the onus back on the developer to ensure that the type really is observably immutable, while still allowing the type to be used in places that require immutable types, namely generic immutable constraints.  Marking a field as unsafe would disable the rule checking only related to that field, and marking a method as unsafe would disable the rule checking only related to that method.  A type that uses unsafe needs to ensure not only that it still puts forth an immutable facade, but that its internal implementation is safe to be used concurrently.\r\n\r\n```C#\r\npublic immutable unsafe struct ImmutableArray<T>\r\n{\r\n    readonly T[] m_array; // Ok, but we’re now responsible again for ensuring immutability\r\n\r\n    private ImmutableArray<T>(T[] array) { m_array = array; }\r\n\r\n    private ImmutableArray<T>(T[] array, T nextItem) : this(new T[array.Length + 1])\r\n    {\r\n        Array.Copy(array, m_array, array.Length);\r\n        m_array[array.Length] = nextItem;\r\n    }\r\n\r\n    public ImmutableArray<T> Add(T item) => new ImmutableArray<T>(m_array, item);\r\n\r\n    public T this[int index] => m_array[index];\r\n    public int Length => m_array.Length;\r\n    ...\r\n}\r\n```\r\n\r\nDelegates could also be marked as immutable, and a set of ImmutableAction and ImmutableFunc types would be included in the framework.  As with other immutable types, all of the objects reachable from an immutable delegate instance would need to be immutable, which means that an immutable delegate could only bind to methods on immutable types.  That in turn means that, when an anonymous method binds to an immutable delegate type, that anonymous method may only capture immutable state.  Further, any locals captured into the lambda must either be from a 'readonly' value (#115) or must be captured by value (#117).  This ensures that the fields of the display class can be 'readonly' and that the method which created the lambda can’t reassign the captured values after creating the lambda.\r\n\r\n```C#\r\npublic void Run()\r\n{\r\n    readonly int local1 = …;\r\n    int local2 = …;\r\n    C local3 = …;\r\n\r\n    ImmutableAction action1 = () => {\r\n        Console.WriteLine(local1.ToString()); // Ok, captured readonly immutable\r\n        Console.WriteLine(local2.ToString()); // Error: ‘local2’ must be captured by value\r\n        Console.WriteLine(local3.ToString()); // Error: ‘local3’ is mutable\r\n    };\r\n\r\n    ImmutableAction action2 = [val local2]() => {\r\n        Console.WriteLine(local2.ToString()); // Ok, captured non-readonly immutable by value\r\n        local2 = 0;                           // Error: ‘local2’ is readonly\r\n    };\r\n}\r\n```\r\n\r\n## Alternatives\r\nThe 'immutable' attribution would be deep, meaning that an instance of an immutable type and all of the types it recursively references in its state would be immutable.  In contrast, we could consider a shallow version, with a 'readonly' attribute that could be applied to types.  As with 'immutable', this would enforce that all fields were readonly.  Unlike 'immutable', it would place no constraints on the types of those fields also being immutable."},"comment":{"url":"https://api.github.com/repos/dotnet/roslyn/issues/comments/73114478","html_url":"https://github.com/dotnet/roslyn/issues/159#issuecomment-73114478","issue_url":"https://api.github.com/repos/dotnet/roslyn/issues/159","id":73114478,"user":{"login":"jods4","id":3832820,"avatar_url":"https://avatars.githubusercontent.com/u/3832820?v=3","gravatar_id":"","url":"https://api.github.com/users/jods4","html_url":"https://github.com/jods4","followers_url":"https://api.github.com/users/jods4/followers","following_url":"https://api.github.com/users/jods4/following{/other_user}","gists_url":"https://api.github.com/users/jods4/gists{/gist_id}","starred_url":"https://api.github.com/users/jods4/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/jods4/subscriptions","organizations_url":"https://api.github.com/users/jods4/orgs","repos_url":"https://api.github.com/users/jods4/repos","events_url":"https://api.github.com/users/jods4/events{/privacy}","received_events_url":"https://api.github.com/users/jods4/received_events","type":"User","site_admin":false},"created_at":"2015-02-05T19:53:34Z","updated_at":"2015-02-05T19:53:34Z","body":"Maybe I'll state the obvious here, but I think that the problem of initializing an immutable graph has some overlap with the problem of initializing non-nullable references, which is another proposal under consideration. For instance, how could I create a graph of non-nullable references? \r\nFiguring out a unified solution to both situations would be interesting."}}