There is some way to implement "with" operator without declaring records? #7848
-
I love records, but sometimes I feel that they limit me a lot in specific things. For example I want to implement a 'readonly struct' that stores 3 strings that will make up part of a domain name, so far without problem. Only that struct has to be immutable, unless I could implement the Why types with `record ' modifier, it implements an equality comparer of its own internally, I can't override that method and I need a specific comparator. You can even implement it with methods. My question is exactly this, is there any decent way to use the features of the `with 'operator without declaring the type as 'record'? Sample: readonly struct Email {
// maybe new keywork "immutable" before struct/class to allow use with operator in custom types that are not records.
readonly string _localPart, _domainPart;
public string LocalPart {
// get => & init =>
}
public string DomainPart {
// get => & init =>
}
}
Email sourceAddr = "[email protected]"; // myuser = LocalPart, mywebsite.com = DomainPart
var targetAddr = sourceAddr with
{
LocalPart = "otheruser";
};
// otheruser = LocalPart, mywebsite.com = DomainPart |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Nevermind, |
Beta Was this translation helpful? Give feedback.
-
And anonymous types. It was championed to find a way to generalize a pattern for |
Beta Was this translation helpful? Give feedback.
-
You can override the way a record implements equality - by explicitly declaring See this Stack Overflow answer for more details and links to more information. |
Beta Was this translation helpful? Give feedback.
You can override the way a record implements equality - by explicitly declaring
bool Equals(R? other)
. The compiler fills in everything else for you.See this Stack Overflow answer for more details and links to more information.