dotnet / dotnet/core

Ref return functions will not allow me to hide an out parameter.

Open
#4,733 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
PowerShell
Stars
22k
Forks
4.9k
Avg merge
5d 5h
Merged PRs (30d)
29

Description

I am trying to implement a pattern akin to Parse() and TryParse() but with ref returns. Because I am using a ref return, I had to put my success bool as an out parameter. My version of the Parse() function will not allow me to use my implementation of TryParse() without _also_ writing the out parameter from TryParse().

It's easier if I show you:
```
public ref T TryGetComponent(out bool success);
public ref T GetComponent() where T : struct
{
bool success;
ref var result = ref TryGetComponent(out success);
if(success)
{
return ref result;
}
throw new Exception("Could not get component.");
}
```
This produces the error:
`"Cannot return 'result' by reference because it was initialized to a value that cannot be returned by reference."`

After some head scratching I realized that this is because it will not let me consume and hide the success out bool parameter. It expects me to return that as an out parameter as well. This compiles, but is not what I want:
```
public ref T TryGetComponent(out bool success);
public ref T GetComponent(out bool success) where T : struct
{
// NOTE: 'success' is now an out var on GetComponent().
ref var result = ref TryGetComponent(out success);
if(success)
{
return ref result;
}
throw new Exception("Could not get component.");
}
```

I would prefer to hide this success out variable completely!

Out of curiosity I figured out that this extends to "ref" arguments as well.

Here are the important dotnet --info stats:
```
.NET Core SDK (reflecting any global.json):
Version: 3.1.100
Commit: cd82f021f4

Runtime Environment:
OS Name: Windows
OS Version: 10.0.18363
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\3.1.100\

Host (useful for support):
Version: 3.1.0
Commit: 65f04fb6db
```

I wasted more time than I care to admit trying to decipher this error message. I would go so far as to call the error message misleading, because it points you at the return variable by name instead of calling out the missing/required out assignment.

This issue strikes me as a compiler limitation, but I would not be surprised if there was a good reason.

My two hopeful outcomes of this issue are:
1) It would be nice to see a less-misleading error message.
2) I would like to consume and encapsulate my out/ref arguments in peace.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.