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 9104057
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T01:46:28+00:00 2026-06-17T01:46:28+00:00

I want to convert a string to a given generic type T . It

  • 0

I want to convert a string to a given generic type T. It may be either basic type or string (e.g. int or string), or an array of a basic types or strings (e.g. int[] or string[]). I have the following function:

T Str2Val<T>(string str)
{
  return (T)Convert.ChangeType(str, typeof(T));
}

It works well for basic types. But it fails for T being an array E[] and str being a comma-separated list of values.

I can easily check whether T is an array with typeof(T).IsArray. Then I have two solutions: parse an array in the same function with a scalar, like the following:

  if (!typeof(T).IsArray)
  {
    return (T)Convert.ChangeType(str, typeof(T));
  }
  else
  {
    // Handle an array
  }

or implement two overloaded functions: one for generic T and second for generic E[]. However, both of solutions fail. I cannot use any array-specific code in the else-clause since it must be compatible with a scalar. And C# cannot pick proper overload with E[] when T is actually an array.

What should I do?

  • 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-06-17T01:46:29+00:00Added an answer on June 17, 2026 at 1:46 am

    I would create some listing of custom parsers that you register then later leverage since you seem to be wanting to use custom rules anyway:

    public static class StringParsers
    {
        private static Dictionary<Type, object> Parsers = new Dictionary<Type, object>();
    
        public static void RegisterParser<T>(Func<string, T> parseFunction)
        {
            Parsers[typeof(T)] = parseFunction;
        }
    
        public static T Parse<T>(string input)
        {
            object untypedParser;
            if (!Parsers.TryGetValue(typeof(T), out untypedParser))
                throw new Exception("Could not find a parser for type " + typeof(T).FullName);
    
            Func<string, T> parser = (Func<string, T>)untypedParser;
    
            return parser(input);
        }
    }
    

    During your application initialization, you would register the types you intend to use later in your application (I’m guessing this is known since you’re using generics):

    StringParsers.RegisterParser<string[]>(input => input.Split(','));
    StringParsers.RegisterParser<int[]>(input => input.Split(',').Select(i => Int32.Parse(i)).ToArray());
    StringParsers.RegisterParser<int>(input => Int32.Parse(input));
    

    Finally, you can call it simply:

    string testArrayInput = "1,2,8";
    
    int[] integers = StringParsers.Parse<int[]>(testArrayInput); // {1, 2, 8}
    
    string[] strings = StringParsers.Parse<string[]>(testArrayInput); // {"1", "2", "8"}
    
    int singleInt = StringParsers.Parse<int>("9999"); //9999
    

    Now, this is a pretty simple implementation. You may wish to extend it so instead of using type Func<string, T> it might use an IStringParser interface and you can provide deeper implementations of the parsing if necessary. Furthermore, you may wish to make it thread safe (unless you’re sure that won’t be an issue, or if you are sure your registration on startup is before any usages)

    EDIT: If you really, really, really want it all in one function just accounting for your comma delimited array, then you can use this:

    public static T Str2Val<T>(string str)
    {
        if (!typeof(T).IsArray)
            return (T)Convert.ChangeType(str, typeof(T));
    
        Type elementType = typeof(T).GetElementType();
    
        string[] entries = str.Split(',');
        int numberOfEntries = entries.Length;
    
        System.Array array = Array.CreateInstance(elementType, numberOfEntries);
    
        for(int i = 0; i < numberOfEntries; i++)
            array.SetValue(Convert.ChangeType(entries[i], elementType), i);
    
        return (T)(object)array;
    }
    

    But this feels so wrong. There must be a better way and to avoid the double generic input in Alexander’s answer, but there you go.

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

Sidebar

Related Questions

I want to convert a string representations of few dozen enum types to enum
I want to convert an string to an enum type using TValue, I googled
I want to convert a String to an array of objects of Character class
I want to convert below string to an array in javascript. {a:12, b:c, foo:bar}
I have a dictionary<String,Object> and I want to convert it to a List<Customer> Is
I have a Character array (not char array) and I want to convert it
I want to convert a string of playing cards given as in A into
In my application i want to convert the given CDT formatted 24 hr string
I have the following ERD and want to convert it EF 4.1 Code First
I want to convert String to Date in different formats. For example, I am

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.