Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / March 2008

Tip: Looking for answers? Try searching our database.

Stupid error with get/set on properties

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
K Viltersten - 19 Mar 2008 08:24 GMT
Can someone, please, tell me what is wrong
with this code?! I get stuck on the "set"
method of the property.

public class Start
{[STAThread]
 public static void Main ()
 { Something some1 = new Something ();
   Something some2 = some1.doSome (); }}

class Something
{public Something () : this (1) { }
 public Something (Something p) : this (p.Some) { }
 public Something (byte s) { this.Some = s; }

 public byte Some
 { get { return this.Some; }
   set { this.Some = value; }}
 public Something doSome ()
 { return new Something (2); }}

The program runs well when i use the default
definition of get/set as:

 public byte Some { get; set; }

but one certainly need to be able to affect
what's being done there. I've been looking at
this for a few days. Either i'm slow or blind,
i can't see the error!

--
Regards
Konrad Viltersten
--------------------------------
sleep    - a substitute for coffee for the poor
ambition - lack of sense to be lazy
Jon Skeet [C# MVP] - 19 Mar 2008 08:40 GMT
> Can someone, please, tell me what is wrong
> with this code?! I get stuck on the "set"
> method of the property.

public byte Some
{
   get { return this.Some; }
   set { this.Some = value; }
}

These calls are recursive - and you haven't declared any actual
storage.

Remember that the properties are just method calls in disguise. As soon
as I rewrite the properties this way, I'm sure you'll see why it
doesn't work:

public byte GetSome()
{
   return GetSome();
}

public void SetSome(byte value)
{
   SetSome(value);
}

You probably *meant* it to be something like this:

// Field backing the property
private byte some;
// Property
public byte Some
{
   // Note case changes
   get { return this.some; }
   set { this.some = value; }
}

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

Peter Duniho - 19 Mar 2008 08:50 GMT
> Can someone, please, tell me what is wrong
> with this code?! I get stuck on the "set"
> method of the property.

Just from the code you posted, it seems like you are also stuck on the  
"get".  That code has unterminated recursion in both the setter and getter  
and will crash with a stack overflow exception using either.

> [...]
> but one certainly need to be able to affect
> what's being done there. I've been looking at this for a few days.  
> Either i'm slow or blind,
> i can't see the error!

No offense, but I vote for "slow".  :)  Or at least (and maybe more  
polite), ill-informed.

The reason the automatic property works is that using that syntax the  
compiler generates the needed member field to store the value for you.  In  
the code you wrote, you don't provide anywhere to store the value.  Even  
worse, you get the property by retrieving the property, and you set the  
property by assigning the property.  Both of those implementations just  
wind up calling the property again over and over until you run out of  
stack.

If you're going to write your own property, you need to provide a place to  
put the data.  The getter and setters need to use this place, rather than  
calling themselves over and over.  A correct implementation might look  
something like this:

    private byte _some;

    public byte Some
    {
        get { return _some; }
        set { _some = value; }
    }

And in fact, this is essentially what the automatic declaration for a  
property does for you.  If this is all you're doing, stick with the  
automatic declaration.  You only need to write it explicitly if you need  
some extra functionality, such as being able to access the backing field  
without going through the property, raising an event when the property  
changes, etc.

If this doesn't clear things up, you might want to actually read the  
documentation on MSDN regarding properties in C#:
http://msdn2.microsoft.com/en-us/library/x9fsa0sw.aspx

Pete
K Viltersten - 19 Mar 2008 10:09 GMT
> No offense, but I vote for "slow".  :)  Or at least (and
> maybe more polite), ill-informed.

Ill-informed it is, then!

I was under impression that the whole thing with
properties is not to use the setter/getter syntax:

 int number;
 public int setNumber (int n) {this.number = n;}
 public void getNumber () {return this.number;}

but on your reply it sounds that it's basically the same
as in C++/Java. Do we have "properties" just for the
same of having something other than "instance
variables"? In that case, i'll be off to kick my friend
who swore that i shouldn't use "byte _info" to carry
the contents presented by "Info"-property.   :)

Thanks a 10^3 for the answer!

--
Regards
Konrad Viltersten
--------------------------------
sleep    - a substitute for coffee for the poor
ambition - lack of sense to be lazy
Jon Skeet [C# MVP] - 19 Mar 2008 10:13 GMT
> > No offense, but I vote for "slow".  :)  Or at least (and
> > maybe more polite), ill-informed.
[quoted text clipped - 7 lines]
>   public int setNumber (int n) {this.number = n;}
>   public void getNumber () {return this.number;}

The point of properties is to make syntax simpler, so you can write:

x.Foo.Bar.Baz

instead of

x.getFoo().getBar().getBaz()

That's really all it is.

> but on your reply it sounds that it's basically the same
> as in C++/Java. Do we have "properties" just for the
> same of having something other than "instance
> variables"?

The point of properties is that they expose data as part of the API
without exposing the details of how that data is stored. A field is
part of the implementation of a class - a (non-private) property is
part of the API.

> In that case, i'll be off to kick my friend
> who swore that i shouldn't use "byte _info" to carry
> the contents presented by "Info"-property.   :)

Well, if you can use an automatic property, you might as well do so
(and the compiler will autogenerate a field). But if you're writing the
property manually, you should absolutely use a field (unless it could
be a more esoteric property, e.g. one which reads its data from a
file).

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk

K Viltersten - 19 Mar 2008 11:11 GMT
>> I was under impression that the whole thing with
>> properties is not to use the setter/getter syntax:
[quoted text clipped - 13 lines]
>
> That's really all it is.

Ah, got it. Thanks.

--
Regards
Konrad Viltersten
--------------------------------
sleep    - a substitute for coffee for the poor
ambition - lack of sense to be lazy
Peter Duniho - 19 Mar 2008 18:36 GMT
> [...]
> Well, if you can use an automatic property, you might as well do so
> (and the compiler will autogenerate a field). But if you're writing the
> property manually, you should absolutely use a field (unless it could
> be a more esoteric property, e.g. one which reads its data from a
> file).

I think this is worth emphasizing: I think the phrase "should absolutely"  
is misleading, since the examples of "a more esoteric property" are  
numerous, and especially since the one example provided seems to imply  
that some dedicated state is still stored somewhere.

In fact, anything that represents some well-defined state which can be  
either retrieved, set, or both could qualify as a property.  A property  
need not have any data behind it directly storing the state at all, not  
even stored somewhere that's an alternative to a plain old field, like a  
database, file, remote process, etc.

Obviously there has to be some state that is affected when setting, and  
some state that is inspected when getting, but in neither case does that  
state need to be dedicated to the property.  I would say that you "should  
absolutely use a field" only when the property is a simple "store and  
retrieve this data" sort of thing.  There are lots of examples of  
properties that don't have dedicated storage for their state.

I know that Jon understands this, but it's my feeling that his use of the  
word "absolutely" conveys an implication that I'm sure he didn't intend.  
His parenthetical qualification of the statement doesn't, I think, go far  
enough in acknowledging the many and varied situations in which you would  
not have a field dedicated to storing a property's state.

Pete
Jon Skeet [C# MVP] - 19 Mar 2008 18:56 GMT
> > [...]
> > Well, if you can use an automatic property, you might as well do so
[quoted text clipped - 7 lines]
> numerous, and especially since the one example provided seems to imply  
> that some dedicated state is still stored somewhere.

Agreed in every respect.

Signature

Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk


Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.