0

I write a function to check data type int32

 public static Int32? ParseInt32(this string text)
        {
            Int32 result;
            if (!Int32.TryParse(text, out result))
                return null;
            return result;
        }

How do I extend this function that supports all data types???

thanks.

4
  • All data types? How about DateTime? Process? SqlException? All of these are types. Commented Jan 10, 2012 at 10:47
  • You can use generics and reflection, but all datatypes may not support TryParse method. So invoking them at run time may lead to exception. So be specific in what kinda datatypes you wish to support? Commented Jan 10, 2012 at 10:47
  • Just int,DateTime,Long,Double Commented Jan 10, 2012 at 11:10
  • 1
    @mohsen: All of those types already have a TryParse method. Commented Jan 10, 2012 at 16:11

3 Answers 3

3

How about something like this:

public static T? TryParse<T> (this string text) where T: struct
{
    T? result = null;

    if (!string.IsNullOrEmpty(text))
    {
        try
        {
            result = (T?) Convert.ChangeType(text, typeof (T));
        }
        catch (InvalidCastException) {}
        catch (FormatException) {}
        catch (OverflowException) {}
    }

    return result;
}

You would then call it like this:

int? myInt = "100".TryParse<int>();

or

DateTime? myDate = "2001-01-01T23.00.00".TryParse<DateTime>();
Sign up to request clarification or add additional context in comments.

3 Comments

That will throw an exception if it can't be converted (although good use of Convert.ChangeType, didn't know of that one).
Thanks George, I realised that as soon as I hit save. Updated to catch parsing exceptions.
What advantage does this method have over int.TryParse, datetime.TryParse, long.TryParse, double.TryParse, etc.?? It seems like you're re-inventing the wheel!
2

Here's a minimal working example:

using System;

namespace ConsoleApplication1
{
    struct Test
    {
        // No TryParse method here!
    }

    static class Program
    {
        static void Main(string[] args)
        {
            var invalidTest = "12345".ParseTo<DateTime>();
            var validTest = "12345".ParseTo<int>();
            var veryInvalidTest = "12345".ParseTo<Test>();

            Console.WriteLine(!invalidTest.HasValue ? "<null>" : invalidTest.Value.ToString());
            Console.WriteLine(!validTest.HasValue ? "<null>" : validTest.Value.ToString());
        }

        public static T? ParseTo<T>(this string test) where T : struct
        {
            var method = typeof(T).GetMethod("TryParse", new Type[] { typeof(string), typeof(T).MakeByRefType() });

            if (method == null)
                throw new Exception(); // or return null or whatever

            var parameters = new object[] { test, null };

            if ((bool)method.Invoke(null, parameters))
            {
                return (T)parameters[1];
            }
            else
                return null;
        }
    }
}

Comments

1

Well for that you can make use of Generics but in the method body you need to make use of the type to parse it out in perticular data type.

you can check this : Using Generic Extension Methods

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.