C # 7 Returning the return value of a property does not compile
While learning C # 7, I stumbled upon Ref return by accident. The GetSingle method below works when I found out that it will return me a link outside. But the GetIns method is throwing me out with a compile time error. Unfortunately I cannot train why and how these GetIns differ from GetSingle. Can someone explain to me?
Error: Expression cannot be used in this context because it might not be returned by reference.
Note that one of the comments suggested this as a duplicate. But this question was about the type of the collection and it was specifically between a member of the collection and a property in the type. So I see this as a different matter.
class Pro
{
static void Main()
{
var x = GetSingle(new int[] { 1, 2 });
Console.WriteLine(x);
}
static ref int GetSingle(int[] collection)
{
if (collection.Length > 0) return ref collection[0];
throw new IndexOutOfRangeException("Collection Parameter!");
}
static ref int GetIns(Shape s)
{
if (s.Area <= 0)
{
s.Area = 200;
return ref s.Area;
}
return ref s.Area;
}
struct Shape {public int Area{ get; set; }
}
source to share
This is because Shape has a scope property and not a public member. You cannot return property references.
This won't compile:
class Shape
{
private int mArea;
public int Area => mArea;
}
static ref int GetIns(Shape s)
{
if (s.Area <= 0)
{
s.Area = 200;
return ref s.Area;
}
return ref s.Area;
}
But it will:
class Shape
{
public int Area;
}
static ref int GetIns(Shape s)
{
if (s.Area <= 0)
{
s.Area = 200;
return ref s.Area;
}
return ref s.Area;
}
source to share