EN
C#/.NET - convert string to short
3 points
In C#/.NET string can be parsed to short in few ways.
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
string text = "123";
8
short value = short.Parse(text);
9
10
Console.WriteLine(value);
11
}
12
}
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
string text = "123";
8
short value;
9
10
if (short.TryParse(text, out value))
11
Console.WriteLine(value);
12
}
13
}
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
using System;
2
3
public class Program
4
{
5
public static void Main()
6
{
7
string text = "123";
8
short value = Convert.ToInt16(text);
9
10
Console.WriteLine(value);
11
}
12
}
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
using System;
2
using System.ComponentModel;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
TypeConverter converter = TypeDescriptor.GetConverter(typeof(short));
9
10
string text = "123";
11
short value = (short)converter.ConvertFrom(text);
12
13
Console.WriteLine(value);
14
}
15
}
Output:
xxxxxxxxxx
1
123
Check this article
The following methodsshort.Parse
,short.TryParse
,Convert.ToInt16
andthrow System.FormatException.
TypeConverter.ConvertFrom