I have an interface which has a property with public get and protected set.
Yet when I implement this in my class i get an error saying it must be public.
My interface looks like this:
public interface ISegment
{
INode NodeA { get; protected set; }
INode NodeB { get; protected set; }
public sealed void SetNodeA(INode node) => NodeA = node;
public sealed void SetNodeB(INode node) => NodeB = node;
}
My class Segment : ISegment
has the properties declared like this:
[SerializeField]
protected Node _nodeA;
public INode NodeA
{
get => _nodeA;
protected set => _nodeA = value as Node;
}
[SerializeField]
protected Node _nodeB;
public INode NodeB
{
get => _nodeB;
protected set => _nodeB = value as Node;
}
And i get this error:
'Segment' does not implement interface member 'ISegment.NodeA.set'
'Segment' does not implement interface member 'ISegment.NodeB.set'
What am i misunderstanding here?
CodePudding user response:
Do it like this
public interface ISegment
{
INode NodeA { get; protected set; }
INode NodeB { get; protected set; }
public sealed void SetNodeA(INode node) => NodeA = node;
public sealed void SetNodeB(INode node) => NodeB = node;
}
public class MyClass : ISegment
{
private Node _nodeA;
private Node _nodeB;
INode ISegment.NodeA
{
get => _nodeA;
set => _nodeA = value as Node;
}
INode ISegment.NodeB
{
get => _nodeB;
set => _nodeB = value as Node;
}
private void Do(INode node)
{
if(node == NodeA) { } // Error
if(node == _nodeA) { } // Warning "Possibly unintended reference comparison"
if (node == ((ISegment)this).NodeA) { } // OK
}
}
but the Question is, why do you want that? Why protected set
?
You can do it like this also. (Not helps here because of default implementation in the interface)
public interface IFoo
{
public string Bar { get; }
}
public class Bubu : IFoo
{
public string Bar { get; protected set; }
}
Update: Edited the code to show more exactly, how to access the properties