C
C#13mo ago
Honza K.

✅ public readonly bool Equals(...)? - SOLVED

I created struct for my needs of representing a phone number prefix and intellisense offered me a "potential fix" which after applying added readonly modifier to a method return type? Can you explain to me what this does as I see it first time in my 5 years of c#-ing?
public struct PhoneNumberPrefix : IEqualityComparer<PhoneNumberPrefix>
{
public PhoneNumberPrefix(int intValue, string stringValue)
{
IntValue = intValue;
StringValue = stringValue;
}
public int IntValue { get; set; } = 0;
public string StringValue { get; set; } = "";

public readonly bool Equals(PhoneNumberPrefix x, PhoneNumberPrefix y)
{
return x.IntValue == y.IntValue && x.StringValue == y.StringValue;
}

public int GetHashCode(PhoneNumberPrefix obj)
{
throw new NotImplementedException();
}
}
public struct PhoneNumberPrefix : IEqualityComparer<PhoneNumberPrefix>
{
public PhoneNumberPrefix(int intValue, string stringValue)
{
IntValue = intValue;
StringValue = stringValue;
}
public int IntValue { get; set; } = 0;
public string StringValue { get; set; } = "";

public readonly bool Equals(PhoneNumberPrefix x, PhoneNumberPrefix y)
{
return x.IntValue == y.IntValue && x.StringValue == y.StringValue;
}

public int GetHashCode(PhoneNumberPrefix obj)
{
throw new NotImplementedException();
}
}
And yes... It compiles 😄
6 Replies
artya
artya13mo ago
So the readonly modifier means that the
Equals
Equals
method is restricted from modifying any data in your struct
Honza K.
Honza K.13mo ago
nvm, I just found the documentation for it 😄 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/readonly-instance-members I wonder if it offers any performance benefits?
Readonly instance members - C# 8.0 draft feature specifications
This feature specification describes the syntax for declaring and using readonly instance members.
artya
artya13mo ago
I highly doubt there are performance benefits The method itself is simple enough to where even if you did gain performance benefits they'd most likely not be noticable
Honza K.
Honza K.13mo ago
reading through the link I posted... it can save you some copies of the structs when using in parameters... so in case of equals method it wont do much, but in case of a bigger structures it can save memory
artya
artya13mo ago
👍 you asked the question and I learned something new today
Honza K.
Honza K.13mo ago
haha, same here, thank you 😄
Want results from more Discord servers?
Add your server
More Posts