How can I use auto-implemented properties with just the 'set' accessor and not using the 'get' accessor?

44 Views Asked by At

In c#, I recently learned that auto-implemented properties can make things easier since it automatically declares a backing private field for us.

Using both the 'get' and 'set' accessors or just the 'get' accessor in the auto-implemented properties to make it read-only was possible, and no errors occured. However, using only the 'set' accessor to make the property write-only resulted in a error.

[accessor must declare a body because property is not marked as 'abstract' or 'extern']

I have no idea why this error occurs. It probably wants me to explicitly create the backing field myself, but that's not the auto-implemented properties are for. Can anyone tell me how to solve this issue, or what I have mistaken?

namespace ConsoleApp1;

public static class AutoImplementedPropTest
{
    public static void Main()
    {
        
    }
}

class C
{
    public int A { set; }
}

class D
{
    public int A { get; set; }
}

class E
{
    private int a;

    public int A
    {
        set
        {
            a = value;
        }
    }
}

This is the code I wrote. No errors in class D and E but only in C.

0

There are 0 best solutions below