Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

C#/.NET - convert string to short

0 contributions
3 points

In C#/.NET string can be parsed to short in few ways.

1. short.Parse method example

using System;
					
public class Program
{
	public static void Main()
	{
		string text = "123";
		short value = short.Parse(text);
		
		Console.WriteLine(value);
	}
}

Output:

123

2. short.TryParse method example

using System;
					
public class Program
{
	public static void Main()
	{
		string text = "123";
		short value;

		if (short.TryParse(text, out value))
			Console.WriteLine(value);
	}
}

Output:

123

3. Convert.ToInt16 method example

using System;
					
public class Program
{
	public static void Main()
	{
		string text = "123";
		short value = Convert.ToInt16(text);
		
		Console.WriteLine(value);
	}
}

Output:

123

4. TypeConverter.ConvertFrom method example

using System;
using System.ComponentModel;

public class Program
{
	public static void Main()
	{
		TypeConverter converter = TypeDescriptor.GetConverter(typeof(short));

		string text = "123";
		short value = (short)converter.ConvertFrom(text);

		Console.WriteLine(value);
	}
}

Output:

123

5. Custom conversion example

Check this article

6. Notes

The following methods short.Parse, short.TryParse, Convert.ToInt16 and TypeConverter.ConvertFrom throw System.FormatException.

7. References

  1. short.Parse(String) - Microsoft Docs
  2. short.TryParse(String, Int16) - Microsoft Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more