0

As I'm writing my code I use this general format

private fields

public/protected properties allowing access as required

etc...

so I have this example struct

public struct SomeStruct {
 private string m_SomeValue;

 public string SomeValue { get=>m_SomeValue; set=>m_SomeValue = value; }
}

and Visual studio is suggesting that I change the property to this

public string SomeValue { readonly get=>m_SomeValue; set=>m_SomeValue = value; }

I've tried to find information on this, and haven't been able to, why is this a suggestion, and why would I want to do this?

RWolfe
  • 103
  • 2
  • You might want to look at https://stackoverflow.com/questions/18292087/accessing-and-changing-structs-as-property-vs-as-field – Progman Jul 08 '23 at 23:56
  • @Progman I understand how structs are different from classes, and how they work, but up until a couple of weeks ago, It's never been suggested that I make a getter readonly, this is a 'new' thing (at least to me), and I don't know why I would when previously my getters have never been marked as such and they've always behaved as expected – RWolfe Jul 08 '23 at 23:59
  • Also consider this: https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil – Klaus Gütter Jul 09 '23 at 04:31

1 Answers1

2

they've always behaved as expected

No, they've just behaved correctly as written. The code without readonly get is wrong, and VS is helping you fix it automatically. I also suggest you do it.

Also your code is very verbose, the equivalent of the correct code is simply this:

public struct SomeStruct 
{
  public string SomeValue { get; set; }
}

Auto-properties automatically have readonly getters. Your properties are just noise, and wrong to boot.

why is this a suggestion, and why would I want to do this?

Because marking a function as readonly allows the compiler to perform additional optimizations, specifically no longer copying the used fields before using them, since it knows the function won't change them.

Blindy
  • 65,249
  • 10
  • 91
  • 131
  • first, my comment regarding behaving as expected was I suppose more 'personal' it behaved as I expected it to, but I will concede that it's wrong nonetheless. second, my code has always been verbose, internally I almost exclusively use the fields unrestricted, and provide whatever public access is actually required third, this part is the answer to the actual question I was asking, is there a link you can post so I can read up on this more? – RWolfe Jul 10 '23 at 19:47
  • You can read more about it [here](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#readonly-instance-members). – Blindy Jul 10 '23 at 22:16