Search code examples
c#intsubstringbytedelphi-7

Can't convert int to byte


I'm in the process of converting a Delphi app to C#, and I came across this:

alength:=1; //alength is a byte
aa:=astring //astring is a string parameter passed into the function containing all this

alength:=strtoint(copy(aa,2,length(aa)-1));

So copy creates a string from part of an existing string, with the first character of the string starting at index 1, not 0 like other languages. It uses this format:

function copy ( Source : string; StartChar, Count : Integer ) : string;

And then strtoint which converts a string to an int.

For my c# conversion of that bit of code, I have:

alength = Convert.ToInt32(aa.Substring(1 ,aa.Length - 1));

which gives me the error Error 131 Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)

Since alength is already type byte, I didn't think I had to cast it?


Solution

  • You're using Convert.ToInt32() when you're assigning a byte. Use Convert.ToByte() instead.

    Even better would be to use TryParse instead to avoid exceptions when the string isn't valid:

    byte alength;
    bool success = Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength);
    

    If the parsing succeedded success will be true, otherwise false. You can define the flow of your program depending on whether the conversion succeeds or not:

    byte alength;
    if(Byte.TryParse(aa.SubString(1,aa.Length - 1), out alength))
    {
       //Great success! continue program
    }
    else
    {
       //Oops something went wrong! 
    }