Quarol
Quarol

Reputation: 11

Converting one numeric type to another by using type.parse(var) in c#

I'm new to c# and I've just encountered some problem with converting. I created 2 variables of different numeric types, just like that:

using System;
namespace Exercise
{
    class Program
    {
        static void Main(string[] args)
        {
            int biggerType = 5;
            short smallerType = short.Parse(biggerType);

            Console.WriteLine(smallerType);
        }
    }
}

Then I tried to convert this int variable to short variable by using short.Parse(biggerType) but the program would not compile as it displays an error: cannot covert from 'int' to 'string'.

Later I tried another way of converting, and I wrote this:

using System;
namespace Exercise
{
    class Program
    {
        static void Main(string[] args)
        {
            int biggerType = 5;
            short smallerType = Convert.ToInt16(biggerType);

            Console.WriteLine(smallerType);
        }
    }
}

This time, though, everything worked just fine. However, it suprised me as I got to know that Convert.ToInt16(biggerType) kind of references to short.Parse().

So my question is, why is that happening?

Upvotes: 0

Views: 400

Answers (1)

Johnathan Barclay
Johnathan Barclay

Reputation: 20363

However, it surprised me as I got to know that Convert.ToInt16(biggerType) kind of references to short.Parse()

No, Convert.ToInt16 only uses short.Parse() internally for the overload that accepts string (and object when a string is passed).

The purpose of short.Parse() is to parse a string representation of an integer into a .NET short.

What you are trying to do is convert between numeric data types, and because short cannot accommodate the range of values that int can, this must be done explicitly, and may cause an exception:

short smallerType = (short)biggerType;

And this is what happens internally when you call Convert.ToInt16(int).


If you were to convert a short to an int, this conversion can be implicit because it is guaranteed to succeed:

short smallerType = default;
int biggerType = smallerType; // Implicit conversion is fine here

A full list of explicit and implicit conversions can be found here.

Upvotes: 1

Related Questions