C
C#4mo ago
Denis

✅ Is it possible to explicitly state that a method wont modify a mutable class?

Assume the following class:
public sealed class MyTest
{
public string SomeString { get; set; }
}
public sealed class MyTest
{
public string SomeString { get; set; }
}
I have an instance of said class, and I wish to process it via some method. I want to explicitly state, that this method will not mutate the class instance. is that possible? E.g., method:
public static string PureReadingMethod(MyTest instance)
=> instance.SomeString + "_Read";
public static string PureReadingMethod(MyTest instance)
=> instance.SomeString + "_Read";
I've looked into freezables, but it doesn't seem like this is relevant for my case. I'd like to make it clear that: - I'm aware of read-only properties, I need to keep the property accessors unchanged - I'm aware of the possibility to pass only the single property value as the method parameter and that strings are immutable, I have more complex classes and I cannot pass each property separately Thank you for your help!
4 Replies
Pobiega
Pobiega4mo ago
[Pure] it doesn't actually do anything, other than indicate "Hey I as the developer promise that this method doesnt mutate anything!"
Denis
Denis4mo ago
That's not bad, but still is a "pinkie pwomise" like you said... If only there was a way to strictly prevent any changes...
Pobiega
Pobiega4mo ago
There isn't, except declaring the property as an immutable type, or removing the setter etc. If you truly need it to be both mutable and immutable at the same time, afaik you have no option but to rely on a pinkie promise.
Denis
Denis4mo ago
Alright, fair point.... Thanks a lot!