- Home /
Cannot implicitly convert type string to list - Why is this?
I am trying to write code that stores a list of strings, and then gets each one individually in a for loop. However, I keep receiving the following error:
Cannot implicitly convert type `string' to `System.Collections.Generic.List<string>'
I have set the code to take the string only from the list but the error persists.
List<string> textName = new List<string>();
void OnGUI()
{
for(int i = 0; i < texts; i++)
{
string tn = textName[i];
textName = GUILayout.TextField(tn); // Name - I have also tried tn.ToString() with the exact same results.
}
}
I don't understand why I am receiving this error.
Also, using a (string) cast doesn't work either.
Edit: Using .ToString() does not resolve the issue, and also using Arrays instead of lists produces a similar error involving the inability to convert string to string[].
This script is an editor script (extends from EditorWindow), could this be the cause of the issue?
I just tried it but the error has not gone. I don't understand because your suggestion should have worked fine
Thank you! I knew it'd be a simple problem like that. I originally had textName as a single string and when I changed it to be a list, I didn't change that part of the code properly.
Thanks again
Glad I could help :)
To help debug something like this in the future, pay attention to the return types. Your error explains everything
You were trying to assign a String to a List, rather than an element in the list.
Answer by EDevJogos · Jan 27, 2017 at 05:43 PM
textName is a list if you want to Add a value to it use textName.Add();
or if you want to change the value of one position use textName[/*index position, like 0 or 1...*/].
I only want to get the data from it, I don't need to add any extra data to it currently.
In this line you're trying to assing something to textName textName = GUILayout.TextField(tn);
If you want to return a value from a List you need to pass the index of the value you want to be returned textName[/*index position, like 0 or 1...*/]
;
tn is just textName[i]
However, I tried textName[0] as a test and the error still didn't go away.
Your answer
Follow this Question
Related Questions
Convert Int to String? 1 Answer
Most efficient way to convert string[] to int [] in C#? 2 Answers
Convert Text to float 3 Answers
Converting 1s and 0s to float 1 Answer