I have a method like this: void m1(string str) and have a class like this:
public class MyClass
{
public bool b1 { set; get; }
//and other properties
}
Now why following code does not cause compile error?
IClass2 _class2 = new Class2();
MyClass c1 = new MyClass();
_class2.m1("abcdef" + c1);
When I debug it, I realized that c1.ToString() has been passed to m1. Why this automatic .ToString() has been occurred? The only thing I could say is that m1 has been defined in IClass2 interface and has been implemented by Class2.
This follows the rules of the C# language specification around string concatenation. See section 7.8.4 of the C# 4 spec (the addition operator)
If you didn’t expect that to happen, may I ask what you expected the result of the
"abcdef" + c1expression to be?Note that
m1,IClass2andClass2are irrelevant to what’s happening here – it’s only the concatenation expression which is really relevant: that’s what’s triggering the call toToString(), regardless of what’s later happening to that string.