✅ Get bytes and append to List c#
im trying to write a method that will append the bytes for value to the stream
Stream
, T will be a variable amount of bytes so im taking it in as a generic type, but Write
doesnt have a generic overload
any ideas what i can do?20 Replies
you have 2 stages
1. convert to byte and write
2. map T to a writer that knows how to convert T to bytes
eg something like this pseudo code
https://gist.github.com/IXLLEGACYIXL/9f65b0ebc2ff38a22b0d779e0c92fd59
@mynarco
got it, thank you, ill try to get this working
what exactly is Converter?
that thing who knows the plan to convert T to bytes
for example you have a Vector3
then you will need some sort of converter who knows how to convert Vector3 to bytes and read Vector3 from bytes
like this?
wait no
i still have no idea how it works
i cant reallyt understand how the psuedocode works? Any way you can provide a working example? Its fine if it only converts 1 type just need an idea of how to add a type conversion
@mynarco ive updated the gist
at the bottom is a sample
or top whereever it is for you
ok looking now
so you jump from converter to converter until you can convert it to bytes
and your primtive converters are used for determing the endless chain
forget about the generic context for now
ok got that down, but how do i define the dictionary then? because Converter takes in a generic..
make foreach converter a non generic class which is capable of instantiating the converter from a Type parameter with activate instance
so your helper is a factory of converters
you can source gen that and your converters
this is how it could look, or atleast thats my source gened code that implements what i tell you
got it, thanks
this is maybe more complex than you need it
as i wanted ful generic compatibility
if you want it fixed like system.text.json then you dont need to worry about all of that too much, generating the extension method would be fine allready
depends what you want
i got it thanks :)
Does T need to be any type? Or are blittable types enough?
The suggestions are (no offense) ridiculous either way
If the types can be blittable, just include
CommunityToolkit.HighPerformance
and use its StreamExtensions
You can just use Stream.Write<T>
on the MemoryStream
then, no need to implement anything yourself
If T should be any type that you defined yourself, I recommend implementing an interface over creating converters:
thank you that works well. i appreciate it :), T is just a number, like byte, ushort, uint, and ulong
Yeah then don't overcomplicate it and just use what's already there
As a side note, in your original code (ByteWriter), you should consider if those fields really need to be public. .NET recommends fields to always be private or protected, properties should be public
$close
If you have no further questions, please use /close to mark the forum thread as answered
Of course. I really appreciate it