Condividi tramite


C# 3.0 Features: Automatic Property (Part 3)

I was about to write this entry in my blog which I found. Before that I got comment in my previous Blog on C# 3.0 Features: Automatic Property (Part 2). The same question came in my mind. What will happen if you try to create an automatic property just with get. The C# 3.0 compiler throws an error. If you try to write

 

//Automatic Property

publicint CustID2

{

get ;

}

The error looks like

 

'ConsoleApplication1.Customer.CustID2.get' must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

 

To many it is very unfortunate because most often we may need to declare read-only property (commonly known as “getter” property). But we do have way to do this

 

The same set of property can be declared as

 

publicint CustID2

{

get ;

privateset ;

}

 

This allows us to create the read-only property.

 

Namoskar!!!

Comments

  • Anonymous
    March 27, 2007
    The comment has been removed

  • Anonymous
    March 27, 2007
    Q: What use would an automatic property that only has a get method serve? A: See below. Q: What would the get method return? A: It would always return the default initialized value for the field, i.e, null for reference types, zero for non-reference types. Q: How would you change what it returns? A: You can't because you cannot access the connected field, you don't even know the name of the field.

  • Anonymous
    December 14, 2007
    With this exciting release of .NET Framework 3.5 I have been exploring its magic and sharing the finding

  • Anonymous
    March 20, 2008
    Agree with Dal - I was reading this thinking, "How the heck can code ever set the property to be able to read from it again?!" Still, I'm writing a WCF service for ASP.NET targeting Framework 3.0 in VS 2008 RTM and it won't do the magic for me! Why not? It's VS 2008's compiler, no? Clearly not. If I change the targetted Framework to 3.5, it builds without the "must declare a body because it is not marked abstract or extern". I can only assume that it uses a different compiler that doesn't have this functionality. There. Maybe I should have thought of that before writing this. Oh well, may as well click Submit now...

  • Anonymous
    November 12, 2008
    dear wriju. jestes pierdolniety, jak lato z radiem.

  • Anonymous
    May 11, 2009
    dalle: It would be nice if it acted like the readonly keyword acts so it can be set only once in the constructor. public var MyVar {get;} public Class() {    MyVar = new Var(); } public void doStuff() {    MyVar = new Var(); // This should give compiler error }