tags:

views:

228

answers:

4

I have a windows application that allows input from pen input on tablet machine.

When required a form (A) will open another form (B) to allow user input.

In form (B) I have the following function to return the decoded value that the user inputs with pen.

private object decodedValue;

public T GetDecodedValue<T>()
{
    return (T)decodedValue;
}

When the user enters a value, in form B, I store the result as follows

string sResult = myInkCollector.Ink.Strokes.ToString();
decodedValue = (object)sResult;

Now in form A there are two fields required that allow data input, one is for Quantity (int) and the other is Price (double). I want to allow form B to accommodate the different types hence that is why I am using generics.

So when form B is accepted, it will return to form A and use the following code

int qty = formB.GetDecodedValue<int>();

or

double price = formB.GetDecodedValue<double>();

This is where the error occurs, when the function 'formB.GetDecodedValue' is called it raises an InvalidCastException at

return (T)decodedValue;

Any ideas on what I am doing wrong? I am over complicating things by using generics?

+1  A: 

You can't cast a string to an int, or a double, you need to use int.Parse or double.Parse.

ilivewithian
Depending on where your code is you may need to do some reflection to decide whether to do the int.Parse or double.Parse by doing an if statement on the typeof the decodedValue.
AaronLS
+2  A: 

I don't think using generics here is cleaner than just doing the cast from form A, but that's not the problem. The problem is that the value being returned isn't of the right type. It's a string, and you can't cast from string to int or double. Assuming you actually want to parse it, you should return a string from form B and form A should use int.TryParse or double.TryParse, handling user input error appropriately.

(This is assuming that Ink.Strokes.ToString() returns text such as "5" or "10.50" - it's not immediately clear to me that that's the case.)

Jon Skeet
+4  A: 

TypeConverter may be your best bet:

return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(decodedValue);

This will often work with string values - beyond that... hit'n'miss.

There is also:

return (T)Convert.ChangeType(decodedValue, typeof(T));

which works differently; try both ;-p

Marc Gravell
+1  A: 

Try this:

return (T)Convert.ChangeType(decodedValue, typeof(T));

You cannot implicitly cast an int to a string for example you must convert. This tool is handy and I have used it for a few things.

Try it out.

Andrew

REA_ANDREW