To cast or not to cast

I have some code that looks a bit like:

private byte ReadSByte(TextReader r)
{
string byteString = "" + (char)r.Read() + (char)r.Read();
byte b = Convert.ToByte(byteString, 16);
return b;
}

so (maybe cheeky or nasty but that is irrelevant) there is some string concatenation
going on there and the idea is that I am reading in 2 characters of hex and
turning them into a byte...

Now TextReader.Read() returns an int. Without the cast one gets the ascii
values appended to each other, the string 'byteString' ends up as something
like "425C" and doesn't convert to a byte too well. With the casts everything
is hunky-dory.

So far everything is ok....

The problem is that Resharper marks the cast as redundant. I agree that there
are flaws to my code there (like I should check for a -1 etc.) but the point
here is that even so the cast is definately NOT redundant! I am forcing a
bit-wise narrowing conversion from int to char instead of a 'ToString()'.

Ronnie


1 comment
Comment actions Permalink

Thank you for the report.
Fixed in build 205

--
Eugene Pasynkov
Developer
JetBrains, Inc
http://www.jetbrains.com
"Develop with pleasure!"
<ronnie@freenet.co.uk> wrote in message
news:7c77a953a6218c7726520b1f380@news.jetbrains.com...
>I have some code that looks a bit like:
>

private byte ReadSByte(TextReader r)
{
string byteString = "" + (char)r.Read() + (char)r.Read();
byte b = Convert.ToByte(byteString, 16);
return b;
}

>

so (maybe cheeky or nasty but that is irrelevant) there is some string
concatenation going on there and the idea is that I am reading in 2
characters of hex and turning them into a byte...

>

Now TextReader.Read() returns an int. Without the cast one gets the ascii
values appended to each other, the string 'byteString' ends up as
something like "425C" and doesn't convert to a byte too well. With the
casts everything is hunky-dory.

>

So far everything is ok....

>

The problem is that Resharper marks the cast as redundant. I agree that
there are flaws to my code there (like I should check for a -1 etc.) but
the point here is that even so the cast is definately NOT redundant! I am
forcing a bit-wise narrowing conversion from int to char instead of a
'ToString()'.

>

Ronnie

>



0

Please sign in to leave a comment.