I was experimenting with the new C#7 features and I found something strange. Given the following simplified scenario:
public struct Command
{
}
public class CommandBuffer
{
private Command[] commands = new Command[1024];
private int count;
public ref Command GetNextCommand()
{
return ref commands[count++];
}
public ref Command GetNextCommand(out int index)
{
index = count++;
return ref commands[index];
}
}
public class BufferWrapper
{
private CommandBuffer cb = new CommandBuffer();
// this compiles fine
public ref Command CreateCommand()
{
ref Command cmd = ref cb.GetNextCommand();
return ref cmd;
}
// doesn't compile
public ref Command CreateCommandWithIndex()
{
ref Command cmd = ref cb.GetNextCommand(out int index);
return ref cmd;
}
}
Why does the second method give me the following compiler error?
CS8157 Cannot return 'cmd' by reference because it was initialized to a value that cannot be returned by reference
I know the compiler can't allow you to return a ref to a var that could end up being dead later on, but I don't really see how having an additional out param changes this scenario in any way.
you can't call ref return method that has ref or out param
this change can be fix it
then when you call this method call it by value