Auto implemented properties in c# 3.0

  • Thread starter Thread starter Satish Itty
  • Start date Start date
S

Satish Itty

What is the advantage of the new auto implemented properties introduced
in ocras?
For example is there any difference between

public string Message;

and

public string Message {get;set;}

Thanks.
 
What is the advantage of the new auto implemented properties introduced
in ocras?

They're a really easy way to implement trivial properties.
For example is there any difference between

public string Message;

and

public string Message {get;set;}

Yes - the latter creates a public property backed by a private field.
The former creates a public field. Making a *field* public is usually
a bad idea - it's an implementation detail which is better hidden in
the API with a property to expose it. That way if you need extra
validation, or to store the field in a different form somehow, you can
still expose the same API even while the underlying implementation (in
terms of storage) changes.

Jon
 
What is the advantage of the new auto implemented properties introduced
in ocras?
For example is there any difference between

public string Message;

and

public string Message {get;set;}

Thanks.

No difference in your example. However, the general difference is that
you can create read-only auto-implemented properties.
 
No difference in your example.

Try doing:

CallSomeMethod (ref something.Message);

when Message is a property. You can't. Fields and properties aren't
the same thing. That's just one example of how the two aren't always
compatible, even in source form.
However, the general difference is that
you can create read-only auto-implemented properties.

That's *a* difference. The most important difference, however, is that
properties are an appropriate part of a public API; fields generally
aren't.

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top