Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override only Get accessor

Tags:

c#

I got an abstract class :

abstract class ClassBase
    {
        public abstract string Test { get; }
    }

I want to derive it and by the way add a set accesor

 class ClassDerive : ClassBase
    {
        string _s;

        public override string Test
        {
            get { return _s; }
            set { _s = value; }
        }
    }

I can't do that because i may not override set

 class ClassDerive2 : ClassBase
    {
        string _s;

        public string Test
        {
            override get { return _s; }
            set { _s = value; }
        }
    }

Syntax error

class ClassDerive3 : ClassBase
{
    string _s;

    public override string ClassBase.Test
    {
        get { return _s; }
    }

    public string Test
    {
        set { _s = value; }
    }
}

Syntax error

Any Idea ???

thx

like image 445
Pitming Avatar asked Jun 25 '09 13:06

Pitming


People also ask

Can you override a getter?

You can always manually disable getter/setter generation for any field by using the special AccessLevel. NONE access level. This lets you override the behaviour of a @Getter , @Setter or @Data annotation on a class.

Can you override a property in C#?

Overriding Properties in C#We can also override the property of a parent class from its child class similar to a method. Like methods, we need to use virtual keyword with the property in the parent class and override keyword with the porperty in the child class.

Why we use get set property in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

What is get and set method in C#?

The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.


1 Answers

You cannot do exactly what you want to do but here is a workaround:

abstract class ClassBase
{
    public abstract String Test { get; }
}

class ClassDerive : ClassBase
{
    string _s;

    public override string Test
    {
        get { return _s; }
    }

    public void SetTest(String test)
    {
        this._s = test;
    }
}

This will make Test only settable in ClassDerived via the public SetTest method. I know this is not as clean as using the property's setter but it is about as good as it's going to get.

like image 129
Andrew Hare Avatar answered Sep 25 '22 11:09

Andrew Hare