I have a class that is implicitly convertible from a string and explicitly convertible from a string. It is not a string, though, and I don't want to replace locations in code with a string, just for the sake of convenience.
When I want to serialize or deserialize an object containing a property that uses this type, I want it to be treated like a string. I know, I could just write a converter (in my case a Json.NET converter), but I would prefer the serialization to be implicit and without any attribute decorations when defining a property of this type.
Is there a possibility to make it easy for the serializer and just get a string from the class when serializing and create an object of the class with the string value inside when deserializing?
This is the code of the class:
public class StringClass
{
private string value;
public StringClass(string s)
{
Validate(s);
value = s;
}
private void Validate(string value)
{
// Some validation happening here, throwing an exception if the input does not match
}
public static implicit operator StringClass(string s) => new(s);
public static explicit operator string(StringClass sc) => sc.value;
public override int GetHashCode() => value.GetHashCode();
public override string ToString() => value;
}
An example for a class where this is in use:
C#
public class TestClass
{
public StringClass Id { get; set; }
public string Name { get; set; }
}
Json
{
"id": "123456789abcdef",
"name": "username"
}
Things I thought about doing:
- Implementing the ISerializable interface. But I think this works only when serializing, not when deserializing.
- Writing a converter but instead of applying it to the property, apply it to the class itself somehow (if that's possible).
I am totally fine with "there is no other option, write a converter that needs to be applied to the property", but I want to know if there is an alternative that allows me to omit the whole attribute-on-property-thing and just make it implicit.