Assign a value to the explicitly implemented readonly interface in the constructor

Same question like this , but for C # 7.0 instead of 6.0:

Is there a way to assign the value of an explicitly implemented read-only (getter-only) interface property in the constructor? Or is it another and the same answer, i.e. Use Bypass Mode?

For example:

interface IPerson
{
    string Name { get; }
}

class MyPerson : IPerson
{
    string IPerson.Name { get; }

    internal MyPerson(string withName)
    {
        // doesn't work; Property or indexer 'IPerson.Name' 
        // cannot be assigned to --it is read only
        ((IPerson)this).Name = withName; 
    }
}

      

Work around:

class MyPerson : IPerson
{
    string _name;
    string IPerson.Name { get { return _name; } }

    internal MyPerson(string withName)
    {
        _name = withName; 
    }
}

      

+3


source to share


2 answers


As with C # 7, it is best to take advantage of expressed properties and constructors to simplify your code a bit:

class MyPerson : IPerson
{
    string _name;
    string IPerson.Name => _name;

    internal MyPerson(string withName) => _name = withName;
}

      

This does not directly address your question: having a means of defining an interface-explicit property from a constructor. There is a suggestion, although this may solve it in the future, but there are no guarantees.



Suggestion: Property scoped fields where it is suggested to allow the context keyword to field

be used in properties to reference the backing field, without explicitly defining the latter. Perhaps this can provide syntax in strings too:

string IPerson.Name { get; }
internal MyPerson(string withName) => IPerson.Name.field = withName;

      

However, the link above is only for discussing the C # repo topic on GitHub. I have not yet been "protected" by the language team, which is the first step towards this, even considered a new feature. so the chances are that it will never be added to the language (but sometimes it all defies the odds sometimes, so never say never ...)

+6


source


No, you still need the same workaround in C # 7. If you referenced an expression that was extended for a constructor, it has no effect that overrides that restriction.



0


source







All Articles