简体   繁体   中英

c# array index type checking

Okay I came across this in some code that a co-worker has just started to support. I've never done anything like this and wouldn't but I was amazed that the compiler did not flag it as an error.

Basically you can see the "strange" behavior with this little snippet:

array[3/4] = 3;

This is allowed even though 3/4, I would think, would return a double. If you change it to:

array[3.0/4] = 3;

You do get a compiler error.

I'm assuming the first doesn't create a compiler error because it does integer division and returns an integer.

Yes, if both parts are integer - the compiler performs an integer division. You get

3 / 4 = 0

When you try to divide double by an integer - you get a double result, which is not a valid index of array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM