Reputation:
[KnownType(typeof(B))]
public abstract class A: IA // string Description { get; }
{
[DataMember(Name = "description")]
public virtual string Description { get; set; }
}
public sealed class B: A
{
public override string Description
{
get
{
return "Custom_Description";
}
}
}
I cannot change my abstract class and I want to forbid using set
in Description
like:
B b = new B();
b.Description = "description";
How to do that? How can I implement set
?
Upvotes: 1
Views: 127
Reputation: 5034
Here are two ways.
Just make setter protected.
public abstract class A: IA
{
public virtual string Description { get; protected set; }
}
This guarantees that 90% of your code can't set Description. But in inheritors of class A you still can try to set Description. And it's compile-time safety
Replace original auto-property to abstract property without setter. Then in class B write implementation for that. And in some another class you can create backing field if you want to have ability to set/get property. This is more secure way, but it can lead you to redudant copy-paste code.
Upvotes: 1
Reputation: 57172
I think your best option is to throw a NotSupportedException in the set accessor:
public sealed class B : A {
public override string Description {
get {
return "Custom_Description";
}
set {
throw new NotSupportedException();
}
}
}
If you want to get a compile error, instead, that's not possible, as you cannot
change the accessibility of the set
method in B
. Even if you could, someone could cast your instance of B
to a type A
and call set on it.
Upvotes: 2
Reputation: 9839
If it is in you abstract class I think it cannot be done. An ugly work around would be:
public sealed class B: A
{
public override string Description
{
get
{
return "Custom_Description";
}
set
{
throw new InvalidOperationException();
}
}
}
You can also discard (take it, but not use it) the value in the setter
Upvotes: 0