Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, immutability and public readonly fields

I have read in many places that exposing fields publicly is not a good idea, because if you later want to change to properties, you will have to recompile all the code which uses your class.

However, in the case of immutable classes, I don't see why you would ever need to change to properties - you're not going to be adding logic to the 'set' after all.

Any thoughts on this, am I missing something?

Example of the difference, for those who read code more easily than text :)

//Immutable Tuple using public readonly fields public class Tuple<T1,T2> {      public readonly T1 Item1;      public readonly T2 Item2;      public Tuple(T1 item1, T2 item2)      {          Item1 = item1;          Item2 = item2;      } }  //Immutable Tuple using public properties and private readonly fields public class Tuple<T1,T2> {      private readonly T1 _Item1;      private readonly T2 _Item2;      public Tuple(T1 item1, T2 item2)      {          _Item1 = item1;          _Item2 = item2;      }      public T1 Item1 { get { return _Item1; } }      public T2 Item2 { get { return _Item2; } }  } 

Of course, you could use auto-properties (public T1 Item1 { get; private set; }), but this only gets you 'agreed immutability' as opposed to 'guaranteed immutability'...

like image 526
Benjol Avatar asked Feb 12 '10 06:02

Benjol


People also ask

Bahasa C digunakan untuk apa?

Meskipun C dibuat untuk memprogram sistem dan jaringan komputer namun bahasa ini juga sering digunakan dalam mengembangkan software aplikasi. C juga banyak dipakai oleh berbagai jenis platform sistem operasi dan arsitektur komputer, bahkan terdapat beberepa compiler yang sangat populer telah tersedia.

C dalam Latin berapa?

C adalah huruf ketiga dalam alfabet Latin. Dalam bahasa Indonesia, huruf ini disebut ce (dibaca [tʃe]).

Bahasa C dibuat pertama kali oleh siapa dan tahun berapa?

Bahasa pemrograman C ini dikembangkan antara tahun 1969 – 1972 oleh Dennis Ritchie. Yang kemudian dipakai untuk menulis ulang sistem operasi UNIX. Selain untuk mengembangkan UNIX, bahasa C juga dirilis sebagai bahasa pemrograman umum.


1 Answers

C# 6.0 now supports auto-property initializers.

The auto-property initializer allows assignment of properties directly within their declaration. For read-only properties, it takes care of all the ceremony required to ensure the property is immutable.

You can initialize read-only properties in constructor or using auto-initializer

public class Customer {     public Customer3(string firstName, string lastName)     {         FirstName = firstName;         LastName = lastName;     }     public string FirstName { get; }     public string LastName { get; }     public string Company { get; } = "Microsoft"; }  var customer = new Customer("Bill", "Gates"); 

You can read more about auto-property initializers here

like image 177
Vlad Bezden Avatar answered Sep 21 '22 05:09

Vlad Bezden