C
C#11mo ago
blokyk

✅ Override (abstract) getter-only property with a setter

Hello! I was wondering if there is anyway to add a setter to an overridden getter-only property? Currently, I've tried the following:
public class Base {
public abstract int Count { get; }
}

public class Derived : Base {
// #1
public override int Count { get; set; } // CS0546: Cannot override because no 'set' accessor

// #2
// CS0106: The 'override' modifier is not valid for this item
// CS0538: 'Base' in explicit implementation is not an interface
override Base.Count => Count;
public new int Count { get; set; }
}
public class Base {
public abstract int Count { get; }
}

public class Derived : Base {
// #1
public override int Count { get; set; } // CS0546: Cannot override because no 'set' accessor

// #2
// CS0106: The 'override' modifier is not valid for this item
// CS0538: 'Base' in explicit implementation is not an interface
override Base.Count => Count;
public new int Count { get; set; }
}
I'd prefer avoiding a constructor, since the rest of my hierarchy uses required properties, and Derived is actually sub-classed elsewhere, so adding a constructor would make things a bit clunky...
8 Replies
Developful
Developful11mo ago
Why not make the count in base a method? therefore it's only get, and you can customize the value as much as you want in the future
blokyk
blokyk11mo ago
As in GetCount() and then declarating a Count prop for Derived? I mean that's what i'm doing in the meantime, but it's pretty clunky
Developful
Developful11mo ago
perhaps protected set?
blokyk
blokyk11mo ago
And also, consumers for Derived might be confused as to why there's both a Count prop and a GetCount() method
Developful
Developful11mo ago
it would still be able to by set by classes that shouldn't set it but
blokyk
blokyk11mo ago
🤔 didn't think about that, why not yeah it's not perfect, but it's less clunky than a method, and they're internal classes so eh 🤷‍♀️
Developful
Developful11mo ago
You could make the set within the base class throw an error at best
blokyk
blokyk11mo ago
yepyep probably what i'm gonna do thank you for the help :)
Want results from more Discord servers?
Add your server
More Posts