-1

When creating an immutable type is there any value in creating a property for the read only fields?

Public readonly fields:

public class MyClass 
{
    public readonly string MyText;

    public MyClass (string theText)     
    {
        MyText = theText;
    }
}

or

Private readonly fields with public propery:

public class MyClass 
{
    private readonly string myText;

    public string MyText    
    {
        get { return myText; }
    }

    public MyClass(string theText)  
    {
        myText = theText;
    }
}
JHJ
  • 303
  • 1
  • 6
  • See [here](https://stackoverflow.com/questions/3917796/how-to-implement-a-read-only-property). I guess you wanted to return the myText in the second code sample. – Peter Schneider Apr 01 '19 at 21:27

2 Answers2

0

Fields are generally meant to contain implementation details. For that reason they should not be declared in a manner that is visible to other code bases. A public, non-internal field would violate this rule. If the caller uses the fields directly, they are violating the general SOLID principle that implementations should depend on abstractions.

In addition, properties have certain advantages over fields. Properties can be included in an interface, for example, while fields cannot. Also, properties can be virtual, abstract, and overridden, while fields cannot.

John Wu
  • 50,556
  • 8
  • 44
  • 80
0

As a complement to @John Wu's answer:

In C# 6 and later you can use read-only properties assignable only in the constructor:

public string MyText { get; }

This relieves you from having a backing-field solely for supporting this property.

But the story does not end here, a property is not a field but a method.

Knowing this, it allows you to achieve things a field would not be able to such as:

Notify of value changes by implementing INotifyPropertyChanged:

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class Test : INotifyPropertyChanged
{
    private string _text;

    public string Text
    {
        get => _text;
        set
        {
            if (value == _text)
                return;

            _text = value;
            OnPropertyChanged();
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Being a value you can bind to:

In WPF and UWP you can only bind to properties, not fields.

In the end:

It depends on your requirements.

aybe
  • 15,516
  • 9
  • 57
  • 105