Forbid string & object concatenation

I am converting a bunch of strings in an api into classes. I am using extensively the compiler to help me with this, since I can replace some types in core apis, and follow the type errors.

However, there is a frustrating source of bugs with this approach:

// linqpad snippet
void Main()
{
    var t = "yay : " + (new Foo());
    t.Dump(); // "yay: namespace.Foo" instead of compilation error
}

class Foo {
}

C# will happily add together a string and any user defined object. Is there a way to turn this into a warning or a compilation error?

I want a compilation error, because this data is ultimately shown to the user. If I miss one concatenation, the users will see class names in the application, which is not really a behavior I want.

Jon Skeet
people
quotationmark

C# will happily add together a string and any user defined object. Is there a way to turn this into a warning or a compilation error?

Yes - if you're using Visual Studio 2015 or higher :)

You can use Roslyn to create your own code diagnostic / code fix, and I believe this lets you escalate the problem from being just a warning to being an error. You can then include this diagnostic in your continuous integration build.

Be careful how far you go with this though - I would normally try to handle this in code review rather than making it an outright error. Creating your own dialect of C# could be a slippery slope...

Note that in some cases, the code you've given could be entirely appropriate - if Foo overrides ToString() for example. Are you really sure you want to ban this?

people

See more on this question at Stackoverflow