Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Custom formatter on nullable value type doesn't work #348

Open
aradalvand opened this issue Nov 2, 2024 · 0 comments
Open

Custom formatter on nullable value type doesn't work #348

aradalvand opened this issue Nov 2, 2024 · 0 comments

Comments

@aradalvand
Copy link

aradalvand commented Nov 2, 2024

Given this Program.cs:

using MemoryPack;
using NodaTime;

Console.WriteLine("Hello, World");

[MemoryPackable]
public partial record TestRequest(
    [property: InstantFormatter]
    Instant Instant1,
    [property: InstantFormatter]
    Instant? Instant2
);

[AttributeUsage(AttributeTargets.All)]
public class InstantFormatter : MemoryPackCustomFormatterAttribute<Instant>
{
    public override IMemoryPackFormatter<Instant> GetFormatter() => new Formatter();

    private class Formatter : MemoryPackFormatter<Instant>
    {
        public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref Instant value)
        {
            writer.WriteValue(value.ToUnixTimeTicks());
        }

        public override void Deserialize(ref MemoryPackReader reader, scoped ref Instant value)
        {
            value = Instant.FromUnixTimeTicks(reader.ReadValue<long>());
        }
    }
}

The build fails:

TestRequest.MemoryPackFormatter.g.cs(34,91): error CS0266: Cannot implicitly convert type 'MemoryPack.IMemoryPackFormatter<NodaTime.Instant>' to 'MemoryPack.IMemoryPackFormatter<NodaTime.Instant?>'. An explicit conversion exists (are you missing a cast?)

Ideally, I shouldn't have to repeat the code in MemoryPack's NullableFormatter<T> + have separate nullable and non-nullable formatters for every value type — this is bad composability. MemoryPack should be smart enough in this example to know that formatter I specified should be wrapped in a NullableFormatter<T>.

Worth noting that MessagePack works this way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant