comn8u
01-05-2007, 08:56 AM
What is the sole purpose of a property? I'm trying to figure you the difference between a method and a property in functionality. You can make a method do everything a property can do right? What is the difference?
|
Click to See Complete Forum and Search --> : Properties Vs. Methods comn8u 01-05-2007, 08:56 AM What is the sole purpose of a property? I'm trying to figure you the difference between a method and a property in functionality. You can make a method do everything a property can do right? What is the difference? felgall 01-05-2007, 04:16 PM properties are like nouns. They have a value or state. methods are like verbs. They perform actions. A property can't perform an action and the only value that a method has is the one that is returned aftewr it finishes performing the action. eg Property - door possible values open closed Method openDoor action is to change the value of the door property to "open". aaronbdavis 01-08-2007, 11:29 AM A property is essentially a wrapper to accessor methods. They are meant to solve a that specific problem (Getting or Setting an internal value). As such they only take one (implicit) argument called value. As I see it, the main reasons to use them in place of methods are thus: The definitions are clearer than the equivalent methods. They are easier to use in the calling environment. You should use them when you need to expose some internal value, but do not want to do so directly (for example, so you can do data validation). Here is an example. Lets say you have an integer member variable called foo that must always be non-negative. You could define accessor methods like so. namespace ns { public class myclass { private int foo = 0; public int setFoo(int value) { if (value >= 0) { this.foo = value; } else { throw new InvalidDataException(); } } public int getFoo(int value) { return this.foo; } } } To use this else where, you would have to call it thus:myclass mc = new myclass(); mc.setFoo(4) If you define the equivalent Property, it would look like this: namespace ns { public class myclass { private int foo; public int Foo { set { if (value >= 0) { this.foo = value; } else { throw new InvalidDataException(); } } get { return this.foo } } } } and call it like this:myclass mc = new myclass(); mc.Foo = 4; // this automatically calls the set portion of the property. scottrickman 01-09-2007, 11:30 AM You can't have a read-only Method but you can have a read-only Property, just one more difference! webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |