简体   繁体   中英

Implicit type conversion of return value

I have a function which returns a long but the value which I return is an integer. I know about implicit casting but technically the function return type doesn't match the return value's type. The code compiles and runs without warnings or errors. What is happening here?

public static long GetIndex(int Index){
  int [] marks = new int[5]  {99, 98, 92, 97, 95};
  return marks[Index];
}

public static void Main(string[] args)
{
  long n = GetIndex(3);
}

Yes, the return statement will apply implicit conversions. Here's a simple example:

public long Method()
{
    int value = 10;
    return value;
}

This is just equivalent to:

public long Method()
{
    int value = 10;
    long valueToReturn = value;
    return valueToReturn;
}

So if you'd expect the second one to work, just think of the first as doing exactly that.

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