Gowtham Raj
Gowtham Raj

Reputation: 173

CS0266 cannot implicitly convert type 'System.Collections.Generic.IEnumerable<char>' to 'string'

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

Answers (3)

Sh.Imran
Sh.Imran

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

user12031933
user12031933

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

Link
Link

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.

  1. Just the + operator
string s = "Hello";
s = s + "World";

Or shorthand:

string s = "Hello";
s += "World";
  1. static Concat function from string
string s = "Hello";
s = string.Concat(s, "World");
  1. String Interpolation
string s = "Hello";
s = $"{s}World";

Upvotes: 4

Related Questions