Reputation: 2234
I have a string array to be defined by user input and I need to convert the string array into a short array so I can use the values for calculations. I need to use an array because I will need to refer to all of the values collectively later. This is what I have:
string [] calIntake = new string[3];
calIntake [0] = Console.ReadLine ();
calIntake[1] = Console.ReadLine ();
calIntake[2] = Console.ReadLine ();
I have tried:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), Short.Parse);
I get an error with this that says: "The type arguments for method 'System.Array.ConvertAll(TInput[], System.Converter)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Then I tried:
short[] calIntakeNum = Array.ConvertAll(calIntake.split(','), ne Converter<string, short>(Short.Parse));
and I get the same error. So how can I convert a string array based on user input into a short array?
Upvotes: 0
Views: 2597
Reputation: 4006
The second method you tried failed because you tried calling a method on a class that doesn't exist, and because Short.Parse
doesn't exist. Removing the .split(',')
from your first parameter to ConvertAll
and changing Short.Parse
to short.Parse
will fix the issue:
short[] calIntakeNum = Array.ConvertAll(calIntake, new Converter<string, short>(short.Parse));
If it's possible for your program, you could declare your array as short[]
originally, and call short.Parse
on Console.ReadLine()
:
short[] shortArray = new short[3];
shortArray[0] = short.Parse(Console.ReadLine());
Upvotes: 0
Reputation: 14894
calIntake
is already an array, you don't need to Split
it. There is no type Short
in C#, there is short
or Int16
short[] calIntakeNum = Array.ConvertAll(calIntake, short.Parse);
Upvotes: 1
Reputation:
You can just project the strings through the short.Parse
method:
short[] calIntakeNum = calIntake.Select(short.Parse).ToArray();
Upvotes: 2