1

I'm writing a code that asks a user for two initials and if they can be converted to chars, prints out the initials. However, I'm finding some strange behavior. Why is it that this code prints out two initials (chars) as expected:

Console.WriteLine(" please put in your first and last initial :");
string firstinitial = Console.ReadLine();
string lastinitial= Console.ReadLine();
char firstin1;
char lastin1;
if (!char.TryParse(firstinitial, out firstin1))
{
   Console.WriteLine("not valid");
}

if (!char.TryParse(lastinitial, out lastin1))
{
    Console.WriteLine("not valid");

}

Console.WriteLine( firstin1 + " " + lastin1);
Console.ReadKey();

and THIS code prints out a number?

Console.WriteLine(" please put in your first and last initial :");
string firstinitial = Console.ReadLine();
string lastinitial= Console.ReadLine();
char firstin1;
char lastin1;
if (!char.TryParse(firstinitial, out firstin1))
{
    Console.WriteLine("not valid");
}

if (!char.TryParse(lastinitial, out lastin1))
{
    Console.WriteLine("not valid");

}
Console.WriteLine(firstin1 + lastin1);
Console.ReadKey();

Obviously the + between two chars is the problem, but why? Is it based on how chars are stored in C#?

sFishman
  • 137
  • 9
  • 2
    A char is a two-byte numeric type. The + operator adds their values. Edit: this is wrong, char is not considered numeric, but implicitly converted to that for the + operator. See duplicate. – CodeCaster Dec 04 '19 at 14:03
  • I believe it's because the underlying ASCII code for the characters. Adding them together adds the ASCII codes together. Try `firstin1.ToString() + lastin1.ToString()` – dvo Dec 04 '19 at 14:03
  • try using , instead of + – niehoelzz Dec 04 '19 at 14:04
  • This may help you with a more elegant way to combine `char` type: (https://www.dotnetperls.com/char-combine) – Ryan Wilson Dec 04 '19 at 14:04

1 Answers1

1

+ operation has different functionality for char and string type objects.

In firstin1 + " " + lastin1 you are doing a concatenation operation with two chars and a string so compiler is treating all objects as strings. In C# ""is used to show that it is a string ''is used for chars.

In firstin1 + lastin1 you are actually doing an addition operation and not combining strings as you are only using char type and the output is expected to be a char.

In simpler terms it is same as 5+1 equals 6 and not 51.

Gusart
  • 11
  • 2