Home > Blockchain >  Is there a way to use different accessibility modifier for a setter in C#11 when using the "req
Is there a way to use different accessibility modifier for a setter in C#11 when using the "req

Time:12-13

Is there a way to use different accessibility modifier for a setter in C#11 when using the "required" keyword?

    public class Person
    {
        
        public required string FirstName { get; protected set; }

        public void ChangeNameToMike()
        {
            FirstName = "Mike";
        }
    }

What I would like to achieve, is that when you instantiate the Person class, you'd need to provide a "FirstName" and you can access the name anywhere, but modifying it should only be possible inside the class and classes that inherit from the Person class. I know that it's possible to achieve this via a constructor, but would like to achieve it with the new required keyword, or something similar, basically to use newer way to write C# code.

The exact error I'm getting is: CS9032 Required member 'Person.FirstName' cannot be less visible or have a setter less visible than the containing type 'Person'.

It works with a constructor, but I wanted to achieve the same result without one.

    public class Person
    {
        
        public string FirstName { get; protected set; }

        public Person(string firstName)
        {
            FirstName = firstName;
        }

        public void ChangeNameToMike()
        {
            FirstName = "Mike";
        }
    }

CodePudding user response:

Similar to the idea here, you can add a protected field, and implement the public get and init accessors explicitly.

public class Person
{
    protected string firstName = "";
    public required string FirstName {
        get => firstName;
        init => firstName = value;
    }

    public void ChangeNameToMike()
    {
        firstName = "Mike";
    }
}

Since the property has a public init accessor, the compiler is happy about the required modifier, and you can set the field when you want to set it.

  • Related