Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 342097
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T10:46:16+00:00 2026-05-12T10:46:16+00:00

This is what I’ve come up with so far, but it doesn’t seem very

  • 0

This is what I’ve come up with so far, but it doesn’t seem very optimal, any ideas on better approaches?

public void ToBytes(object[] data, byte[] buffer)
{
    byte[] obytes;
    int offset = 0;

    foreach (object obj in data)
    {
        if (obj is string)
            obytes = System.Text.Encoding.UTF8.GetBytes(((string)obj));
        else if (obj is bool)
            obytes = BitConverter.GetBytes((bool)obj);
        else if (obj is char)
            obytes = BitConverter.GetBytes((char)obj);
        // And so on for each valuetype

        Buffer.BlockCopy(obytes, 0, buffer, offset, obytes.Length);
        offset += obytes.Length;
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-12T10:46:16+00:00Added an answer on May 12, 2026 at 10:46 am

    Well, you could have a map like this:

    private static readonlyDictionary<Type, Func<object, byte[]>> Converters = 
        new Dictionary<Type, Func<object, byte[]>>()
    {
        { typeof(string), o => Encoding.UTF8.GetBytes((string) o) },
        { typeof(bool), o => BitConverter.GetBytes((bool) o) },
        { typeof(char), o => BitConverter.GetBytes((char) o) },
        ...
    };
    
    public static void ToBytes(object[] data, byte[] buffer)
    {
        int offset = 0;
    
        foreach (object obj in data)
        {
            if (obj == null)
            {
                // Or do whatever you want
                throw new ArgumentException("Unable to convert null values");
            }
            Func<object, byte[]> converter;
            if (!Converters.TryGetValue(obj.GetType(), out converter))
            {
                throw new ArgumentException("No converter for " + obj.GetType());
            }
    
            byte[] obytes = converter(obj);
            Buffer.BlockCopy(obytes, 0, buffer, offset, obytes.Length);
            offset += obytes.Length;
        }
    }
    

    You’re still specifying the converter for each type, but it’s a lot more compact than the if/else form.

    There are various other ways of constructing the dictionary, btw. You could do it like this:

    private static readonly Dictionary<Type, Func<object, byte[]>> Converters = 
            new Dictionary<Type, Func<object, byte[]>>();
    
    static WhateverYourTypeIsCalled()
    {
        AddConverter<string>(Encoding.UTF8.GetBytes);
        AddConverter<bool>(BitConverter.GetBytes);
        AddConverter<char>(BitConverter.GetBytes);
    }
    
    static void AddConverter<T>(Func<T, byte[]> converter)
    {
        Converters.Add(typeof(T), x => converter((T) x));
    }
    

    I see another answer has suggested binary serialization. I’m personally not keen on “opaque” serialization schemes like that. I like to know exactly what’s going to be in the data in a way that means I can port it to other platforms.

    I would point out, however, that your current scheme doesn’t give any sort of delimiter – if you have two strings, you’d have no idea where one stopped and the other started, for example. You also don’t store the type information – that may be okay, but it may not be. The variable length issue is usually more important. You might consider using a length-prefix scheme, like the one in BinaryWriter. Indeed, BinaryWriter may well be a simpler solution in general. You’d probably want to still have a map of delegates, but make them actions taking a BinaryWriter and a value. You could then build the map by reflection, or just a hardcoded list of calls.

    Then you’d just initialize a BinaryWriter wrapping a MemoryStream, write each value to it appropriately, then call ToArray on the MemoryStream to get the results.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This might seem like a stupid question I admit. But I'm in a small
this is probably a stupid question but I can't seem to find the answer.
This should be simple, but the answer is eluding me. If I've got a
this is my code that I write it but I want to use LINQ
This is probably a stupid question, but how much of a security risk is
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
This must be a very simple solution that has eluded me this last hour.
This has been posted, but I've tried lot of solutions found on SO and
This is a pretty stale question but frankly I'm yet to find it answered
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.