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

  • Home
  • SEARCH
  • 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 462523
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T23:04:59+00:00 2026-05-12T23:04:59+00:00

I want to parse a string into a type easily, but I don’t want

  • 0

I want to parse a string into a type easily, but I don’t want to write wrapper code for each type, I just want to be able to do “1234”.Parse() or the like and have it return 1234. This should work for any type that has parsing capabilities.

  • 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-12T23:04:59+00:00Added an answer on May 12, 2026 at 11:04 pm

    My solution works for any type that implements the static method TryParse(string, out T), whether it’s a class or a struct. Also, it will work for nullable structs, e.g.

    "1234".Parse<int>() == 1234
    "asdf".Parse<int>() == 0 // i.e. default(int)
    "1234".Parse<int?>() == 1234
    "asdf".Parse<int?>() == null
    "2001-02-03".Parse<DateTime?>() == new DateTime(2009, 2, 3)
    

    and since System.Net.IPAddress has TryParse,

    "127.0.0.1".Parse<IPAddress>().Equals(new IPAddress(new byte[] { 127, 0, 0, 1 }))
    

    I create the code with the System.Linq.Expressions framework, and then cache the created lambda. Since this is done in a generic static class with a specified type, this happens only once per type to parse.

    public static class StringExtensions
    {
        /// <summary>
        /// Parse the <paramref name="target"/> as a <typeparamref name="T"/>. If this cannot be achieved, return the default value of <typeparamref name="T"/>.
        /// </summary>
        /// <typeparam name="T">The type to parse into.</typeparam>
        /// <param name="target">The string to parse.</param>
        /// <returns>The resultant <typeparamref name="T"/> or the default of <typeparamref name="T"/>.</returns>
        /// <example>
        /// <code>
        /// "1234".Parse&ltint&gt;() == 1234;
        /// "a".Parse&ltint&gt;() == 0;
        /// "a".Parse&ltint?&gt;() == null;
        /// "2010-01-01".Parse&lt;DateTime?&gt;() == new DateTime(2010, 1, 1)
        /// "2010-01-01a".Parse&lt;DateTime?&gt;() == null
        /// "127.0.0.1".Parse&lt;System.Net.IPAddress&gt;().Equals(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }))
        /// "".Parse&lt;System.Net.IPAddress&gt;() == null
        /// </code>
        /// </example>
        public static T Parse<T>(this string target)
        {
            return ParseHelper<T>.Parse(target);
        }
    
        /// <summary>
        /// Parse the <paramref name="target"/> as a <typeparamref name="T"/>. If this cannot be achieved, return <paramref name="defaultValue"/>
        /// </summary>
        /// <typeparam name="T">The type to parse into.</typeparam>
        /// <param name="target">The string to parse.</param>
        /// <param name="defaultValue">The value to return if <paramref name="target"/> could not be parsed.</param>
        /// <returns>The resultant <typeparamref name="T"/> or <paramref name="defaultValue"/>.</returns>
        /// <example>
        /// <code>
        /// "1234".Parse&ltint&gt;(-1) == 1234;
        /// "a".Parse&ltint&gt;(-1) == -1;
        /// "2010-01-01".Parse&lt;DateTime?&gt;(new DateTime(1900, 1, 1)) == new DateTime(2010, 1, 1)
        /// "2010-01-01a".Parse&lt;DateTime?&gt;(new DateTime(1900, 1, 1)) == new DateTime(1900, 1, 1)
        /// "127.0.0.1".Parse&lt;System.Net.IPAddress&gt;(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 })).Equals(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 }))
        /// "".Parse&lt;System.Net.IPAddress&gt;(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 })).Equals(new System.Net.IPAddress(new byte[] { 0, 0, 0, 0 }))
        /// </code>
        /// </example>
        public static T Parse<T>(this string target, T defaultValue)
        {
            return ParseHelper<T>.Parse(target, defaultValue);
        }
    
        private static class ParseHelper<T>
        {
            private static readonly Func<string, T, T, T> _parser;
    
            static ParseHelper()
            {
                Type type = typeof(T);
                bool isNullable = false;
                if (type.GetGenericArguments().Length > 0 && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                {
                    isNullable = true;
                    type = type.GetGenericArguments()[0];
                }
    
                ParameterExpression target = Expression.Parameter(typeof(string), "target");
                ParameterExpression defaultValue = Expression.Parameter(typeof(T), "defaultValue");
                ParameterExpression result = Expression.Parameter(typeof(T), "result");
                if (isNullable)
                {
                    Type helper = typeof(NullableParseHelper<>);
                    helper = helper.MakeGenericType(typeof(T), type);
                    MethodInfo parseMethod = helper.GetMethod("Parse");
                    _parser = Expression.Lambda<Func<string, T, T, T>>(
                        Expression.Call(parseMethod, target, defaultValue),
                        target, defaultValue, result).Compile();
                }
                else
                {
                    MethodInfo tryParseMethod = (from m in typeof(T).GetMethods()
                                                 where m.Name == "TryParse"
                                                 let ps = m.GetParameters()
                                                 where ps.Count() == 2
                                                    && ps[0].ParameterType == typeof(string)
                                                    && ps[1].ParameterType == typeof(T).MakeByRefType()
                                                 select m).SingleOrDefault();
    
                    if (tryParseMethod == null)
                    {
                        throw new InvalidOperationException(string.Format("Cannot find method {0}.TryParse(string, out {0})", type.FullName));
                    }
                    _parser = Expression.Lambda<Func<string, T, T, T>>(
                        Expression.Condition(
                            Expression.Call(tryParseMethod, target, result),
                            result,
                            defaultValue),
                        target, defaultValue, result).Compile();
                }
            }
    
            public static T Parse(string target)
            {
                return _parser.Invoke(target, default(T), default(T));
            }
    
            public static T Parse(string target, T defaultValue)
            {
                return _parser.Invoke(target, defaultValue, default(T));
            }
    
            private static class NullableParseHelper<TBase> where TBase : struct
            {
                private static readonly Func<string, TBase?, TBase, TBase?> _parser;
    
                static NullableParseHelper()
                {
                    MethodInfo tryParseMethod = (from m in typeof(TBase).GetMethods()
                                                 where m.Name == "TryParse"
                                                 let ps = m.GetParameters()
                                                 where ps.Count() == 2
                                                    && ps[0].ParameterType == typeof(string)
                                                    && ps[1].ParameterType == typeof(TBase).MakeByRefType()
                                                 select m).SingleOrDefault();
    
                    if (tryParseMethod == null)
                    {
                        throw new InvalidOperationException(string.Format("Cannot find method {0}.TryParse(string, out {0})", typeof(TBase).FullName));
                    }
                    ParameterExpression target = Expression.Parameter(typeof(string), "target");
                    ParameterExpression defaultValue = Expression.Parameter(typeof(TBase?), "defaultValue");
                    ParameterExpression result = Expression.Parameter(typeof(TBase), "result");
                    _parser = Expression.Lambda<Func<string, TBase?, TBase, TBase?>>(
                        Expression.Condition(
                            Expression.Call(tryParseMethod, target, result),
                            Expression.ConvertChecked(result, typeof(TBase?)),
                            defaultValue),
                        target, defaultValue, result).Compile();
                }
    
                public static TBase? Parse(string target, TBase? defaultValue)
                {
                    return _parser.Invoke(target, defaultValue, default(TBase));
                }
            }
        }
    }
    

    pants!

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

Sidebar

Related Questions

I work in VBA, and want to parse a string eg <PointN xsi:type='typens:PointN' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
I'm want to parse a custom string format that is persisting an object graphs
I want to download and parse webpage using python, but to access it I
Background I want to be able to parse Javascript source in a Delphi Application.
I want to parse a config file sorta thing, like so: [KEY:Value] [SUBKEY:SubValue] Now
I want to parse some HTML in order to find the values of some
I want to parse a web page in Groovy and extract all of the
I want to parse an Apache access.log file with a python program in a
In my C++ program I want to parse a small piece of XML, insert
I want to pause input in a shell script, and prompt the user for

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.