Page 189 - CSharp/C#
P. 189
Take care to not confuse auto-property or field initializers with similar-looking expression-body
methods which make use of => as opposed to =, and fields which do not include { get; }.
For example, each of the following declarations are different.
public class UserGroupDto
{
// Read-only auto-property with initializer:
public ICollection<UserDto> Users1 { get; } = new HashSet<UserDto>();
// Read-write field with initializer:
public ICollection<UserDto> Users2 = new HashSet<UserDto>();
// Read-only auto-property with expression body:
public ICollection<UserDto> Users3 => new HashSet<UserDto>();
}
Missing { get; } in the property declaration results in a public field. Both read-only auto-property
Users1 and read-write field Users2 are initialized only once, but a public field allows changing
collection instance from outside the class, which is usually undesirable. Changing a read-only
auto-property with expression body to read-only property with initializer requires not only removing
> from =>, but adding { get; }.
The different symbol (=> instead of =) in Users3 results in each access to the property returning a
new instance of the HashSet<UserDto> which, while valid C# (from the compiler's point of view) is
unlikely to be the desired behavior when used for a collection member.
The above code is equivalent to:
public class UserGroupDto
{
// This is a property returning the same instance
// which was created when the UserGroupDto was instantiated.
private ICollection<UserDto> _users1 = new HashSet<UserDto>();
public ICollection<UserDto> Users1 { get { return _users1; } }
// This is a field returning the same instance
// which was created when the UserGroupDto was instantiated.
public virtual ICollection<UserDto> Users2 = new HashSet<UserDto>();
// This is a property which returns a new HashSet<UserDto> as
// an ICollection<UserDto> on each call to it.
public ICollection<UserDto> Users3 { get { return new HashSet<UserDto>(); } }
}
Index initializers
Index initializers make it possible to create and initialize objects with indexes at the same time.
This makes initializing Dictionaries very easy:
var dict = new Dictionary<string, int>()
{
https://riptutorial.com/ 135

