Cause
This error comes up when you tries to append two strings with the “+” sign. As the + sign in C# is a arithmetical operator so you cannot use this too append two string type values. To use “+” the values or variables must be if numeric type.
As C# uses doesn’t supports implicit typecasting, for string concatenation use “&” sign.
Example
string varTest = “”;
string str1 = “abc”;
int str2=21;
varTest = str1 + str2;
The above stqatmet will cause in error stating “Operator + cannot be applied to operands of type string and method group“. Because we are trying to add a string variable in a numeric variable.
To remove the error you must convert all the numeric (integer) datatype or variables to string.
varTest = str1 & str2.ToString();
The output of the above code will be abc21
Conclusion
We must convert all values to a uniform datatype before storing them into a variable.
December 14, 2008 at 7:02 am |
Also, the ony time I’ve ever seen that error is when you try to use the plus operator with a value and a method (ie, you forgot to use parens). Example:
int y = 5 + SomeClassInstance.SomeMethod;
That will raise an the error you show. The line should read:
int y = 5 + SomeClassInstance.SomeMethod(); // Notice the parens at the end.
September 3, 2009 at 4:17 pm |
I think you also can get this if you inadvertently try to iterate through an IEnumerable with a for loop.