Daniel Robinson
Daniel Robinson

Reputation: 14848

c# public property inaccessible

[DataContract]
public class UniqueNamedItem
{
    [DataMember]
    int Id { public get; protected set; }
    [DataMember]
    string Name { public get; protected set; }
}

[KnownType(typeof(UniqueNamedItem))]
[DataContract]
public class BasicNode : UniqueNamedItem
{
    [DataMember]
    SortedList<string, BasicNode> Children { public get; private set; }

    public void addChild(BasicNode bn)
    {
        this.Children.Add(bn.Name, bn);
    }
}

Can you tell me why inside my addChild function the call to bn.Name is not valid even though the UniqueNamedItem.Name property has a public get accessor?

Upvotes: 3

Views: 2776

Answers (6)

Jon Hanna
Jon Hanna

Reputation: 113222

The default access is private, because if you make something public when it should really be private, it won't stop any correct code from working, and it could be that way for years before you realise (and it's also a breaking change to then fix it).

If on the other hand you make something private when it should be public, something will stop working immediately, you go on stackoverflow, a bunch of people say it's private, you fix it, and all is well.

Hence it's a sensible default.

Upvotes: 1

Oded
Oded

Reputation: 498904

The default accessibility for members of classes is private.

So Id and Name are private.

You need to add the correct access modifiers (I added public, you may have meant protected):

[DataContract]
public class UniqueNamedItem
{
    [DataMember]
    public int Id { public get; protected set; }
    [DataMember]
    public string Name { public get; protected set; }
}

One good reason to always declare the accessibility you want.

Upvotes: 12

Chris Beemster
Chris Beemster

Reputation: 362

Your properties are not explicitly marked as public, thus C# automatically considers them to be private.

So:

[DataContract]
public class UniqueNamedItem
{
    [DataMember]
    int Id { public get; protected set; }
    [DataMember]
    public string Name { public get; protected set; }
}

Upvotes: 1

Greg Owens
Greg Owens

Reputation: 3878

You need to make your properties public:

[DataContract]
public class UniqueNamedItem
{
    [DataMember]
    public int Id { public get; protected set; }
    [DataMember]
    public string Name { public get; protected set; }
}

Upvotes: 1

EkoostikMartin
EkoostikMartin

Reputation: 6911

You need to declare your properties as public (see below). The default is private.

[DataContract]
public class UniqueNamedItem
{
    [DataMember]
    public int Id { public get; protected set; }
    [DataMember]
    public string Name { public get; protected set; }
}

Upvotes: 1

Jay
Jay

Reputation: 57899

The UniqueNamedItem.Name property itself is private; you need to explicitly mark the property as public.

The modifiers on accessors can only restrict access further, not increase it.

Upvotes: 4

Related Questions