Jake
Jake

Reputation: 16837

C# virtual automatic properties omit get / set

Is it ok to omit get or set in an automatic property when it is declared virtual?

I am referring a book on C# which shows the members of System.Exception as follows :


// Properties
public virtual IDictionary Data { get; }
public virtual string HelpLink { get; set; }
public Exception InnerException { get; }
public virtual string Message { get; }
public virtual string Source { get; set; }
public virtual string StackTrace { get; }
public MethodBase TargetSite { get; }

If automatic properties need to have both get and set, then why is it ok here?

Thanks.

Upvotes: 3

Views: 1253

Answers (2)

user7116
user7116

Reputation: 64078

This looks like an abbreviated signature for the properties, rather than their actual implementation.

I've not gone to reflector, but you could imagine the above signature for Exception.Data being implemented in one of two manners:

public virtual IDictionary Data
{
    get { return _someInternalImplementation; }
}

Or:

public virtual IDictionary Data
{
    get { return _someInternalImplementation; }
    private set { _someInternalImplementation = value; }
}

All the implementor needs to know is that they may only have a public getter in their override.

Upvotes: 3

Bas
Bas

Reputation: 27105

This shows metadata about this type. It does not specify an automatic property. Automatic properties have no use if they only have one accessor.

It basically shows which properties are there and which ones are read only (that probably have a private setter.

Upvotes: 4

Related Questions