0

Why do I have to use .ToString() for this code to work:

confirmedAcceptance = int.Parse(dr["confirmedAcceptance"].ToString());  

This creates error:

confirmedAcceptance = int.Parse(dr["confirmedAcceptance"]);  
aalhussein
  • 31
  • 3
  • 2
    Looks like XY problem. What type `dr` is? What is the return type of `dr`'s indexer? If `dr` stands for `DataRow`, that you don't need neither `Parse`, nor `Convert`. Just cast value to appropriate type, like this, if that field is really `int` one: `confirmedAcceptance = (int)dr["confirmedAcceptance"];` – Dennis Dec 14 '20 at 11:56
  • Full explanation: [Uses Of Int.Parse, Convert.ToInt32, And int.TryParse (c-sharpcorner.com)](https://www.c-sharpcorner.com/article/uses-of-int-parse-convert-toint-and-int-tryparse/) –  Dec 14 '20 at 17:28

2 Answers2

0

int.Parse tries to parse the certain Object into an INT. This can go as far as converting a string to INT (in which he calculates it) there is no certain way we know if it actually will work. Thats why we have TryParse which instantly catches the Programm if it actually not works

Convert uses a manually programmed Conversion. like Convert.ToInt() it has implicit Conversions for Double/Etc.

So if u know that it is supported, always use Convert, if u maybe dont know whats coming in and have to poker a bit. Use Parse and if best TryParse..

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    "always use Convert" sounds very, very out-and-out. I'd say "do not use `Convert` class unless you really need it" – Dennis Dec 14 '20 at 12:09
0

The ‘Parse’ method accepts a string as a parameter. https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-5.0 The ‘Convert’ method also accepts a string as a parameter. https://learn.microsoft.com/en-us/dotnet/api/system.convert.toint32?view=net-5.0

When you pass an integer to Int.Parse() or Convert.ToInt32() methods you are not passing the correct data type to the method.