C
C#•4mo ago
Kye

Access values from a record without explicitly calling .Value

To keep it quite short, I have a record as followed
public record ConfigurationValue<T>
{
public T Value { get; init; }
}
public record ConfigurationValue<T>
{
public T Value { get; init; }
}
Now when I wanna use it, I simply do something like
public ConfigurationValue<string> TestString { get; set; }
public ConfigurationValue<string> TestString { get; set; }
The annoying part is, upon deserializing it and wanting to access it, I need to do TestString.Value. Is there a way to change the code snippet to simply not use .Value at all? Quite new to records.
8 Replies
Thinker
Thinker•4mo ago
How are you using this record? Also btw you can change this to public record ConfigurationValue<T>(T Value);
Kye
Kye•4mo ago
I did actually change it a lot. I even attempted to use an implicit operator to convert it automatically however, it worked only for non-list values. To answer your question, im mainly using it as a regular model structure except, I am utilizing the record for extensive support. so
public string TestString { get; set; }
public string TestString { get; set; }
is how I am using, just with the record of course.
Kouhai
Kouhai•4mo ago
There is no way to access Value implicitly, and you can't also rely on implicit casting because it won't work when T is an interface
Kye
Kye•4mo ago
I figured mid-way through that the implicit operator wouldn't work So I reverted the code back to its original state
Thinker
Thinker•4mo ago
And since Value is T then you can't really just "forward" the properties from T So no, there is no good way to do this
Kye
Kye•4mo ago
mhm, I was originally planning to keep the .Value in as annoying as it might be I just don't wanna always explicitly call .Value when it can be shortened to just TestString I mean how wrong is this
public static implicit operator T(ConfigurationValue<T> getValue) => getValue.Value;
public static implicit operator T(ConfigurationValue<T> getValue) => getValue.Value;
😭
Kouhai
Kouhai•4mo ago
It'll work for non interface types, but the moment T is an interface it won't work 😅
Kye
Kye•4mo ago
yeah, I realized the hassle and simply kept the .Value in