0

I'm Running the following program in C # :

using System;

class MainClass {
    public static void Main (string[] args) {
        char seed = 'a';
        char EndValue='z';
        while ( seed <= EndValue){
            Console.WriteLine(seed);
            seed+=(char)1;   
        }
    }
}

This works fine but changing the seed+=(char)1; to seed = seed + (char)1;

It throws error

exit status 1

main.cs(9,8): error CS0266: Cannot implicitly convert type int' to char'. An explicit conversion exists (are you missing a cast?) Compilation failed: 1 error(s), 0 warnings" in repl.it

https://repl.it/@nkshschdv/iteration-over-char-variable

Community
  • 1
  • 1

1 Answers1

1

Lets have a look at what your code is actually doing. If i is an int

i += 1 is the same as i = i + 1

So in your case seed+=(char)1; is the same as seed = (char)(seed + 1);

So seed = seed + (char)1; is just missing the char conversion which is implicit in the way you are doing it.

You can also write it seed = (char)((int)seed + 1); but C# handles the char to int conversion for the + operator automatically. As Dennis_E pointed out, because of this implicit int conversion you can just call seed++;

MikeS159
  • 1,884
  • 3
  • 29
  • 54