C
C#6mo ago
mellowzippy

✅ Readonly methods

My VSCode is telling me to change my methods to readonly. I can't find a good explanation anywhere as to what this does and why it's recommended. So I'd really like an explanation from someone who knows.
public struct Note(Book book, List<Entry> entries) : IEnumerable<Entry>
{
public Book book = book;
public List<Entry> entries = entries;

public Note(Book book) : this(book, []) { }

public Note(Book book, Entry entry) : this(book, [entry]) { }

public readonly void Add(Entry entry)
{
entries.Add(entry);
}

public readonly void Remove(string title)
{
foreach (Entry entry in entries)
{
if (entry.Title == title)
{
entries.Remove(entry);
}
}
}

public IEnumerator<Entry> GetEnumerator()
{
return entries.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public struct Note(Book book, List<Entry> entries) : IEnumerable<Entry>
{
public Book book = book;
public List<Entry> entries = entries;

public Note(Book book) : this(book, []) { }

public Note(Book book, Entry entry) : this(book, [entry]) { }

public readonly void Add(Entry entry)
{
entries.Add(entry);
}

public readonly void Remove(string title)
{
foreach (Entry entry in entries)
{
if (entry.Title == title)
{
entries.Remove(entry);
}
}
}

public IEnumerator<Entry> GetEnumerator()
{
return entries.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
5 Replies
Angius
Angius6mo ago
readonly methods in structs basically say that the method does not modify the state of the struct
mellowzippy
mellowzippyOP6mo ago
But it does right..? My methods modify my Entries property.
Angius
Angius6mo ago
It modifies the contents of this list It doesn't modify the state of the struct That is, it doesn't do entries = new List<Entry>() for example Also, it's not a property, it's a field
mellowzippy
mellowzippyOP6mo ago
oooo okay $close
MODiX
MODiX6mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server