Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C# compiler be configured to give warning when explicit cast may cause data loss?

Is there a way to configure the VS2008 C# compiler to give a warning for code like this:

Int64 x = 123456789000;
Int32 y = (Int32)x;
like image 333
HBFan Avatar asked Feb 25 '10 14:02

HBFan


People also ask

Is Can-C good for dogs?

SAFE FOR HUMANS AND DOGS - Can-C is the first and only patented NAC eye drop that uses the exact formula proven effective in both animal and human trials, offering a non-invasive alternative to cataract surgery. EVERY BLINK HYDRATES and lubricates the eye and cornea.

Can-C Eye Drops benefits?

Can-C's ingredients help to soothe and rejuvenate tired eyes, help with macular degeneration, cataracts, and other age-related eye disorders. Can-C eye drops for cataracts contain lubricants, an antioxidant and an anti-glycating agent, N-Acetyl-Carnosine (NAC).

How long can you use can-c eye drops?

Do not use this medication for longer than 3 to 4 days at a time.

Is Can-C approved by FDA?

Can-C is packaged as an eye lubricant because it is not approved by the FDA as a drug to treat cataracts. Besides an eye lubricant it may also be helpful for eye strain, ocular inflammation, blurred vision, dry eye, corneal disorders and retinal diseases.


1 Answers

The whole point of an explicit cast is to say that "I take responsibility for the problem, please just do it."

In your trivial case, it would perhaps be easy for the compiler to figure out that the value would not fit in a Int32, and thus produce your warning.

However, what about this:

Int64 x = CallSomeMethod();
Int32 y = (Int32)x;

How can it warn you about this? Should it:

  1. try to figure out what kind of range the value from CallSomeMethod could return?
  2. always warn? (then what would the point be?)

The best you can hope for here is to have a runtime check, or similar, the compiler cannot prevent you from everything that could go wrong.

like image 171
Lasse V. Karlsen Avatar answered Oct 05 '22 03:10

Lasse V. Karlsen