C# 7 Ref return on a property doesn't compile

c#, c#-7.0

Solution

This happens because Shape has a property Area and not a public int field member. You can not return references to properties.

This wont 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 this 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;
}

Problem

While learning c# 7, I happen to stumble on Ref return. The GetSingle method below works as I learned which return me a reference outside. But GetIns method throws me out with a compile-time error. Unfortnately, I can't workout why and how these GetIns different from GetSingle. Can someone explain me? Error: An expression cannot be used in this context because it may not be return by reference. Please note one of the comment was proposing this as a duplicate. But that question was type of collection and this was specifically between member of a collection and a property in a type. Hence I see this as a different question ``` 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; } } ```

Original source

Related problems