implementing a read/write field for an interface that only defines read
Posted
by
PaulH
on Stack Overflow
See other posts from Stack Overflow
or by PaulH
Published on 2011-01-06T21:02:31Z
Indexed on
2011/01/12
22:53 UTC
Read the original article
Hit count: 227
I have a C# 2.0 application where a base interface allows read-only access to a value in a concrete class. But, within the concrete class, I'd like to have read/write access to that value. So, I have an implementation like this:
public abstract class Base
{
public abstract DateTime StartTime { get; }
}
public class Foo : Base
{
DateTime start_time_;
public override DateTime StartTime
{
get { return start_time_; }
internal set { start_time_ = value; }
}
}
But, this gives me the error:
Foo.cs(200,22): error CS0546: 'Foo.StartTime.set': cannot override because 'Base.StartTime' does not have an overridable set accessor
I don't want the base class to have write access. But, I do want the concrete class to provide read/write access. Is there a way to make this work?
Thanks, PaulH
Unfortunately, Base
can't be changed to an interface as it contains non-abstract functionality also. Something I should have thought to put in the original problem description.
public abstract class Base
{
public abstract DateTime StartTime { get; }
public void Buzz()
{
// do something interesting...
}
}
My solution is to do this:
public class Foo : Base
{
DateTime start_time_;
public override DateTime StartTime
{
get { return start_time_; }
}
internal void SetStartTime
{
start_time_ = value;
}
}
It's not as nice as I'd like, but it works.
© Stack Overflow or respective owner