20

In c++ this code would work:

char c='a'; 
int r=2;
c+=r;

This would do the same as c='c'. How can I do the same in c#?

Programer
  • 1,005
  • 3
  • 22
  • 46

1 Answers1

27

Just cast it to char before adding it to c

char c='a'; 
int r=2;
c += (char) r;
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • @meyou: Just make sure `c` initial value is not `y` or `z` then it will increment to junk characters. – Nikhil Agrawal May 14 '12 at 12:27
  • 2
    hmm I wonder why `char c = 'a' + (char)2;` gives a compilation error? – Andy Jan 25 '13 at 22:31
  • 4
    You can do `char c = (char)('a' + 2);` instead – juergen d Jan 26 '13 at 10:48
  • @Andy the reason this happens is because any operation on byte-sized integers has implicit conversion to int - i.e. `'a' + 2` is really `(int)'a' + 2` and so you need to cast it back. IIRC, this is a C++ backwards-compatibility thing but there's quite a bit of discussion on this question: http://stackoverflow.com/questions/941584/byte-byte-int-why – Rob Church May 08 '13 at 14:05