0

I've tried searching for this and I suspect I'm not asking the question in the right way but I am curious--apart from the obvious differences, what's the difference between charArray.ToString() and new String(charArray)?

This is what I'm talking about:

var cArray = new char[]{'a','b','c'};
var a = cArray.ToString();
var a2 = new String(cArray);
Console.WriteLine($"{a}");
// -> System.Char[]
Console.WriteLine($"{a2}");
// -> abc

Why doesn't cArray.ToString() give me back a string?

Onorio Catenacci
  • 14,928
  • 14
  • 81
  • 132
  • 1
    `Why doesn't cArray.ToString() give me back a string?` - it does, just not the one you are expecting. – GSerg Jul 26 '19 at 15:37
  • 2
    The ToString() method of an array is the default implementation inherited from Object, which simply returns GetType().Name or something. By the way, `a` and `a2` are strings already. You don't need to stringify them again. You could as well write `$"{$"{a}"}"`. Or `$"{$"{$"{a.ToString()}"}".ToString()}"`. – 15ee8f99-57ff-4f92-890c-b56153 Jul 26 '19 at 15:38
  • I've been trying to follow the last part of your comment @EdPlunkett but I'm not following you. Are you saying I could use `Console.WriteLine($"a");` instead of `Console.WriteLine($"{a}");`? What exactly do you mean by _stringify_? – Onorio Catenacci Jul 31 '19 at 14:39
  • @OnorioCatenacci "Stringify" means "turn it into a string". Consider `int n = 3;`: It's an integer, not a string. `string s = $"{n}";` is one way to stringify `n`. Of course, `Console.WriteLine(n);` works just fine. It takes `object` as a parameter. You can pass it anything, and it will stringify the parameter internally. What you are doing is taking strings `a` and `a2`, and converting them into strings all over again in order to pass them to a method that doesn't care if they're strings or not. `a` is already a string. Don't convert it to a string. It IS a string. – 15ee8f99-57ff-4f92-890c-b56153 Jul 31 '19 at 14:42
  • @EdPlunkett Oh, ok, I see what you mean now! Thanks for the explanation and the pointer! – Onorio Catenacci Jul 31 '19 at 16:30

0 Answers0