0

My team follows the general .NET convention that you should expose public properties on your types rather than exposing fields. However, I've come across a class which mostly exposes fields... but then contains this for its two 'identifying' pieces of data:

public readonly int WidgetId;
public readonly string WidgetName;

I am really heavily tempted to refactor these into properties, i.e.

public int WidgetId { get; }
public string WidgetName { get; }

So they match the conventions of the rest of the class. I'm aware of the arguments for and against public fields versus properties. But, given that readonly-auto-properties in particular are a relatively new C# feature, I want to know:

What are the semantic differences between public readonly int Foo and public int Foo { get; }, if any? Are they meaningfully different to the compiler?

Dan J
  • 16,319
  • 7
  • 50
  • 82
  • @PeterDuniho it does not seem to me a duplicate. The question is about readonly properties and fields, not about readonly and private keywords. – Backs Dec 05 '17 at 03:45
  • @Backs: _"not about readonly and private keywords"_ -- of course it is. `readonly` applies _only_ to fields. A "read-only" property is simply one without an accessible setter. Whether the inaccessibility is because the setter simply isn't present or because it's `private` is completely irrelevant. This is still in its essence a question identical to all the others that have been asked over the years. – Peter Duniho Dec 05 '17 at 03:47
  • I'm fine with this being marked duplicate if it funnels to information that materially answers the question. Unfortunately, since the **readonly-auto-property** feature in C# is relatively new, a lot of what's in the linked threads doesn't really apply. The thing I found that *strictly* answers the question "how do a public readonly field and a public readonly property differ in semantics?" is [here](https://www.red-gate.com/simple-talk/dotnet/.net-framework/whats-new-in-c-6/), which demonstrates the IL for a public readonly property: looks like there's no semantic difference. – Dan J Dec 05 '17 at 04:04

1 Answers1

1

Your new property is equal to:

private readonly string _widgetName = GetWidgetName();
public string WidgetName
{
    get { return _widgetName; }
}

So, the value is stored in _widgetName and it's safe because it's readonly, and you can't change it's value as before.

With property WidgetName you can only change access to field _widgetName, not the value. For example:

private readonly string _widgetName = GetWidgetName();
public string WidgetName
{
    get 
    {
        if (_widgetName == null) throw new Exception("Value is not set"); 
        return _widgetName; 
    }
}

You get more control to your data, but in common case - there is no difference, if you just replcae readonly field to readonly propery.

Some information about properties is here.

Backs
  • 24,430
  • 5
  • 58
  • 85