The + operator cannot be applied to operands of the type string and method group.

I check if a directory exists with this code:

while (Directory.Exists(currentDirectory + year.ToString)) { // do stuff year++; } 

year is a normal integer, currentDirectory is a string. Unfortunately, this operation gives me the "Operator" + "cannot be applied to operands of the type" string "and" group of methods ", a mesage error. I do not want to create a new line for each iteration, when I only need to increase it.

+6
source share
4 answers

ToString is a method. You must call him; so you are missing () after ToString .

Change it to

 while (Directory.Exists(currentDirectory + year.ToString())) { // do stuff year++; } 

And it should work :)

+21
source

You missed a call to the ToString method

 while (Directory.Exists(currentDirectory + year.ToString)) 

Must read

 while (Directory.Exists(currentDirectory + year.ToString())) 
+3
source

You are missing year.ToString()

 while (Directory.Exists(currentDirectory + year.ToString)) 

It should be

 while (Directory.Exists(currentDirectory + year.ToString())) { // do stuff year++; } 
+1
source

Missing parentheses () after ToString . You need to change it to the following:

 while (Directory.Exists(currentDirectory + year.ToString())) { // do stuff year++; } 
+1
source

All Articles