Reputation: 173
I'm a newbie to C#. When I run this program, I'm getting a compile type error
CS0266 cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'string'
Is my syntax wrong?
class Program
{
static void Main(string[] args)
{
string s = "Hello";
s = s.Concat("World");
}
}
Upvotes: 0
Views: 1777
Reputation: 1033
No need to go for complex and advanced techniques being a newbie.
In this scenario, concatenation can be done in simple way:
class Program
{
static void Main(string[] args)
{
string s = "Hello";
s = s + "World";
}
}
Upvotes: 0
Reputation:
Concat
is a Linq extension method that allows to concat two IEnumerable<char>
, so you need to write that to convert the resulting array in a string:
s = new string(s.Concat("World").ToArray());
Here the s
value as an array of chars, that is an IEnumerable<char>
, is executing the Concat
method on it using the same thing for the string provided as parameter (an array of chars).
But you may prefer writing, with a space, this standard string
concatenation:
s += " World";
That is the same of:
s = s + " World";
Enumerable.Concat(IEnumerable, IEnumerable) Method
Upvotes: 2
Reputation: 1711
You getting this error because the Concat
function you have called is from LINQ. See here Enumerable.Concat. As a string is basically an enumeration of characters.
You have a variety of options to concatenate strings.
string s = "Hello";
s = s + "World";
Or shorthand:
string s = "Hello";
s += "World";
Concat
function from stringstring s = "Hello";
s = string.Concat(s, "World");
string s = "Hello";
s = $"{s}World";
Upvotes: 4