简体   繁体   中英

Does any .net language support returning ref type

In one of his blogs Eric Lippert said:

Finally, the CLR does allow “ref return types”; you could in theory have a method “ref int M() { … }” that returned a reference to an integer variable. If for some bizarre reason we ever decided to allow that in C#

Does either VB or F# support this? I was thinking of various ways to do strongly typed properties collection, without using reflection...

UPDATE: as of C#7 this is supported.

According Eric Lippet - C# does support this feature.

it is entirely possible to create a version of C# which supports both these features. You could then do things like

static ref int Max(ref int x, ref int y) 
{ 
  if (x > y) 
    return ref x; 
  else 
    return ref y; 
} 

and then call it with

int a = 123;
int b = 456; 
ref int c = ref Max(ref a, ref b); 
c += 100;
Console.WriteLine(b); // 556!

you can read more on his answer to a question regarding return ref types in C#:

Why doesn't C# support the return of references?

As for you question about VB - the language doesn't support it:

Return By-Reference?

Although functions can pass variables by reference, they cannot return them that way. When a function returns, its local variables do not exist anymore (or are pending cleanup if they are heap-allocated). Functions therefore always return by value; because the local variables don't have valid memory addresses anymore, there aren't any variable references to return.

Putting it all together, when you return an object from a function, the only thing that is copied is the address of the object. When you return a value type from a function, the value itself is copied.

This means reference types are essentially value types, wherein the value is the memory address of an object on the heap, (or Nothing)

Source: VB.NET, Is Object Returned by Reference from Function

I couldn't find the same info for F# but I guess it will be the same as VB - so the answer - you can't return ref in F#.

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