Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"FormatException" not thrown when ToInt32() method has invalid argument type

Tags:

c#

.net

console

1)

class Program
{
    static void Main(string[] args)
    {
        int a;
        a = Convert.ToInt32( "a" );
        Console.Write(a);
    }
}

I get FormatException with message: Input string was not in a correct format. and this is quite understood.

2)

class Program
{
    static void Main(string[] args)
    {
        int a;
        a = Convert.ToInt32( Console.Read() );
        Console.Write(a);
    }
}

In second case, I can type any characters, for example abc and it displayed in console.

Question: Why doesn't throw FormatException in second case and why it works successfully with non int characters?

UPDATE

with Console.ReadLine() method, which returns string type, also not trown FormatException and printed any character in console successfully.

class Program
{
    static void Main(string[] args)
    {
        int a;
        a = Convert.ToInt32(Console.ReadLine());
        Console.Write(a);
    }
}
like image 439
Oto Shavadze Avatar asked Nov 29 '22 10:11

Oto Shavadze


1 Answers

The return type of Console.Read() is an int.

You then call Convert.ToInt32(int):

Returns the specified 32-bit signed integer; no actual conversion is performed.

like image 60
CodeCaster Avatar answered Dec 04 '22 13:12

CodeCaster