0

I am new to C# and needing some help. If someone could explain why this is happening and not just give me an answer, that would be much appreciated.

I get the following error message:

Cannot implicitly convert string to int

Here is my code:

int[] arrayData = new int[12];

StreamReader scores = new StreamReader("scores.txt")

while (scores.Peek() != null)
{
    arrayData[counter] = scores.ReadLine();  // <-- above error occurs here
    counter = counter + 1;
}

scores.Close();

I also have one other question if someone can help.

string x = …
int y = …
if (x > y) …  // <-- below errors occurs here 

Error messages:

Operator > cannot be applied to string and int

stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
urang18
  • 15
  • 2
  • 7
  • The content of the `score` array is string... You need to take some cast into account after reading from the file, before putting into the `int` array. – User Oct 05 '14 at 08:13
  • A `string` is not an `int`, you can't compare them or assign the value of one to another... What happens if you tried to compare the string %&* to 6? What would the framework do? In order to get an `int` from your string you must parse it using `int.Parse` or `int.TryParse` then if the parse is successful you can use the return value – Charleh Oct 05 '14 at 08:16
  • It is best to separate the material in your post into two separate questions. – i alarmed alien Oct 05 '14 at 08:16
  • Off-topic advice: `StreamReader` implements [`IDisposable`](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx "MSDN reference page"). Therefore you should put it in a [`using` block](http://msdn.microsoft.com/en-us/library/yh598w02.aspx "MSDN reference page"): `using (StreamReader scores = new StreamReader(…)) { /* use scores */; scores.Close(); }`. This will make sure that even in the case of an unexpected exception, the stream is closed/released properly when execution flow leaves that block. (The explicit call to `Close` would no longer be required, but it also doesn't hurt.) – stakx - no longer contributing Oct 05 '14 at 08:36
  • 1
    Normally it's best to separate questions as suggested by i alarmed alien, but in this case don't because it's actually the same problem. This kind of incredibly basic question is normally not well received on Stack Overflow. What rescued it is your statement that you were less interested in the solution and more interested in understanding the nature of the problem. Well done. – Peter Wone Oct 05 '14 at 08:39
  • I know it's a basic question as I have just starting studying C# but Thank you to everyone for your input, it is much appreciated and I have more of an understanding now. – urang18 Oct 06 '14 at 06:13
  • Your use of LINQ to do a one-liner bulk conversion is clever and elegant, although for large arrays it could produce a spike in memory consumption. My word, they grow up fast! :) – Peter Wone Oct 06 '14 at 23:32

4 Answers4

3

The ReadLine() method returns a string and you are assigning it to an element of an int[] which is an array of int. Because it's the wrong type, the compiler checked whether there was an automatic conversion between the type you are assigning (string) and the type of the variable to which you are assigning it (int). But no implicit conversion from string to int exists, because not all strings can be converted to ints. Hence you "cannot implicitly convert string to int".

What can you do about this situation? In this case, while there is no implicit conversion, there may be an explicit conversion.

string foo = scores.ReadLine();
array[counter] = int.Parse(foo);

Of course this assumes that the line of text that you read into foo contains nothing but a number rendered as text. If there's other stuff you will need to parse the string, which is a whole lot more involved.

Your second question about the comparison is actually the same problem - when you try to compare two different types implicit conversion is attempted and fails. Then you get an error message that you can't compare them. The solution is the same: convert the string to an int using int.Parse(string) as per my example above.

You could convert the int to a string like this:

string ystring = y.ToString();

Then you could compare x with ystring because they're both strings. But this is probably a bad idea, because numbers than have been converted to strings sort differently from how they sort as numbers:

1
10
2

In Hossein's answer you may notice that he uses Convert.ToInt(string) rather than int.Parse(string). They do the same thing, but Convert is a static object exporting a wide variety of conversions. Given that you are only just now learning about type compatibility, you probably aren't ready for the complexity of Convert class. But don't let that stop you from examining it and reading all the documentation for it on http://msdn.microsoft.com because you will find it both educational and useful.

Peter Wone
  • 17,965
  • 12
  • 82
  • 134
  • Thank you Peter, I know the question was quite basic as I have only just started to study c#. But your answers have been very helpful and the explanations help me understand more now. – urang18 Oct 06 '14 at 08:14
2

Short Answer:
Use either

int.Parse();
Convert.ToInt32();

methods like this :

int[] arrayData = new int[12];

StreamReader scores = new StreamReader("scores.txt")

while (scores.Peek() != null)
{
    arrayData[counter] = int.Parse(scores.ReadLine());  
    counter = counter + 1;
}

scores.Close();

You need to convert the string value to int so that you can assign it or use it in comparisons such as

if (x > y) …

Long Explanation:
The error is self explanatory, You are reading an string and are trying to assign it to a whole different type! The ReadLine() method returns a string, And string is different than int.
In C# you have different types and for each of them you must use a compatible value.
int is number (actually a number is an integer so you use int to store and work with numbers ( integer values).
string is an array of characters such as

"Ali","Alex","Apple",....

anything which is placed between a double quote is considered a string in c#.
so basically

1 doesn't equal to "1"

Although they look the same, they are completely different.(its as if you compare a picture of an apple with a real one! they look the same, but they are completely two different things!)

So if you need to extract that number out of the string, you need conversion and in that case if you want to have a conversion you can use Convert.ToInt() method you may also use :

Int32.Parse();

Have a look at here And Also a similar question here

For the same reason you can not use such operators on different types.

So to cut a long story short, you need to do this :

int[] arrayData = new int[12];

StreamReader scores = new StreamReader("scores.txt")

while (scores.Peek() != null)
{
    arrayData[counter] = int.Parse(scores.ReadLine());  
    counter = counter + 1;
}

scores.Close();
Community
  • 1
  • 1
Hossein
  • 24,202
  • 35
  • 119
  • 224
  • Thank you Hossein for your answers and links, it has help me understand a lot more now. – urang18 Oct 06 '14 at 08:11
  • @Urang18: You're welcome. Now, you need to accept one of the answers which helped you the most, as the answer. – Hossein Oct 06 '14 at 11:35
  • After everyone's answers and me understanding a lot more, I did further research and a came up with this option. int[] scoresInt = arrayData.Select(int.Parse).ToArray(); Thanks again – urang18 Oct 06 '14 at 13:58
1

While a string can contain a textual representation of a valid int number (such as "1"), it is not an int (1). A string could also be something other than the textual representation of an integer number, e.g. "ABC", and it clearly wouldn't make sense to have a comparison such as "ABC" > 1, right? This is one reason why the > operator is not defined for the combination of a string and an int: it would not be guaranteed to be meaningful in all cases.

The reason why int x = Console.ReadLine(); doesn't work is the same: that method returns a string, and your variable is typed int. These types are not implicitly convertible.

Here's what you need to do: Convert the textual representation of an integer number inside the string into an int, using int.Parse or int.TryParse:

string text = Console.ReadLine(); // get user input; we cannot know whether a number
                                  // was entered or something else!

int a = int.Parse(text); // might throw an exception if `text` doesn't contain
                         // a textual representation of a valid int number
int b;
if (int.TryParse(text, out b))
{
    // contents of `text` could be converted to an `int`, which is now stored in `b`
}
else
{
    // contents of `text` could not be converted to an `int`, but no exception
    // has been thrown; instead we end up here.
}
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
-1

The string content of the primary array must be converted to the type of the destination array, is which integer... So here it comes:

while (scores.Peek() != null)
{
    arrayData[counter] = Convert.ToInt32(score.ReadLine());
    counter = counter + 1; 
}
stakx - no longer contributing
  • 83,039
  • 20
  • 168
  • 268
User
  • 952
  • 2
  • 21
  • 43
  • Better. But what is that "primary array" you mention? (`scores.ReadLine()` would return a `string`, not a `string[]`.) – stakx - no longer contributing Oct 05 '14 at 08:26
  • @stakx: As a matter fact, I did consider the content of the aforementioned file as an of array strings, due to feeding procedure of the mentioned data structure into the method. – User Oct 05 '14 at 08:30