1

I need help understanding why my program is throwing this error:

Cannot convert from 'string' to 'int'

when both list and tVal are strings.

I am getting this error at

List<string> testitems = new List<string>(tVal);

Please advise.

abc is an int array with some random numbers.

static void Main()
{
    string tVal = "";

    List<int> result = new List<int>();

    for (int i = 0; i < abc.Length; i++)
    {
        if (abc[i] == 7)
        {
            result.Add(0);
            i++;
        }
        else
        {
            result.Add(abc[i]);
        }

        foreach (var item in result)
        {
            tVal += item.ToString();
        }                            
    }

    List<string> testitems = new List<string>(tVal);
    //more code
}
1
  • 5
    You are calling this constructor overload. Apparently you meant new List<string>() { tVal };. Commented Jun 6, 2020 at 19:04

3 Answers 3

3

To add objects to a list you can use:

List<string> testitems = new List<string>() { tVal };  //(like @GSerg suggested in the comments)

Or:

List<string> testitems = new List<string>();
testitems.Add(tVal);
Sign up to request clarification or add additional context in comments.

Comments

2

Put the tVal into a curly brackets , like this:

List<string> testitems = new List<string>() { tVal };

Official documentation for lists: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netcore-3.1

Comments

1
new List<string>(tVal)

You handed tVal in as the 1st constructor argument. The closest match the compiler can find is List<T>(Int32). Wich has a string -> Int conversion that is not valid.

This is not the way to initialize a collection! You can either:

  • use the constructor that can take just about any generic collection as input (List<T>(IEnumerable<T>))
  • Add the single element manually after creating the list (charbels solution)
  • use the collection initializer syntax (as shown by Marci)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.