Home > csharp > In C#, ++c and c += 1 are not always equivalent

In C#, ++c and c += 1 are not always equivalent

csharp> char c = 'a'
csharp> ++c
'b'
csharp> c += 1
(1,7): error CS0031: Constant value `1' cannot be converted to a `char'
csharp>
Advertisements
Categories: csharp Tags: ,
  1. July 7, 2017 at 11:53

    This is completely expected behavior. With `c++` you’re incrementing a `char`; with the second, you’re attempting to add an `int` to a `char` and there is no implicit conversion between these types in this direction. You can make it work by casting the `1` to a `char`: `c += (char) 1;`

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: