Lucina
Lucina

Reputation: 490

Throw a warning/error when implicitly converting from X to Y in Visual C#

Is it possible to selectively treat certain implicit type conversions as errors, or at least generate warnings when they happen?

Bad:

long x = 5; //warning, 5 is an int
float f = 10;// warning, 10 is an int


Good:

long x = 5L; //correct, no warning
float f = 10f; //correct, no warning

Edit: removed reference to bugs, since that isn't the point of the question, and isn't helpful.

Upvotes: 2

Views: 224

Answers (2)

SliverNinja - MSFT
SliverNinja - MSFT

Reputation: 31651

If you were using Visual Studio Premium+, you may be able to create a Code Analysis ruleset to handle this during build time.

You could also write your own VS.NET extension and possible integrate with Roslyn to interrogate the code to the extent that the compiler is.

Upvotes: 1

jason
jason

Reputation: 241711

No, this is not possible. These are legal by the language specification.

Frankly, I'm not even seeing the subtle bugs that the examples you provide could cause.

Upvotes: 0

Related Questions