Girardi
Girardi

Reputation: 2811

How to cast a built-in struct to a parameter type T on C#?

I'm programming a method to query something for the user on the Console and getting his answer... Something like this:

static T query<T>(String queryTxt)
    {
        Console.Write("{0} = ", queryTxt);
        T result;
        while (true)
        {
            try
            {
                result = // here should go the type casting of Console.ReadLine();
            }
            catch (FormatException e)
            {
                Console.WriteLine("Exception: {0};\r\nSource: {1}", e.Message, e.Source);
                continue;
            }
            break;
        }
        return result;
    }

In short, this method should keep asking for the value of queryTxt, where T is always int or double...

Any good way to do this?

Thanks in advance!

Upvotes: 1

Views: 158

Answers (3)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

One way to generalize it is to pass conversion function as delegate. Something like:

T query<T>(string text, Func<string, T> converter)
{... result = converter(Console.Readline())...}
query("foo", s=>Int.Parse(s));

For more generic approach - read "Generalized Type Conversion " http://msdn.microsoft.com/en-us/library/yy580hbd.aspx and related articles.

Upvotes: 1

sisve
sisve

Reputation: 19781

Using type converters.

public static T Query<T>() {
    var converter = TypeDescriptor.GetConverter(typeof (T));
    if (!converter.CanConvertFrom(typeof(String)))
        throw new NotSupportedException("Can not parse " + typeof(T).Name + "from String.");

    var input = Console.ReadLine();

    while (true) {
        try {
            // TODO: Use ConvertFromInvariantString depending on culture.
            return (T)converter.ConvertFromString(input);
        } catch (Exception ex) {
            // ...
        }
    }
}

Upvotes: 2

Chen Kinnrot
Chen Kinnrot

Reputation: 21015

if its always int or double work with double.Parse and it'll always work.

Upvotes: 2

Related Questions