Understanding Methods


In addition to properties, most objects have methods. Methods are actions the object can perform, in contrast to attributes that describe the object. To understand this distinction, think about the Pet object example. A Dog object has a certain set of actions that it can perform. These actions, called methods in Visual C#, include barking, tail wagging, and chewing carpet (don't ask). Figure 3.6 illustrates the Dog object and its methods.

Figure 3.6. Invoking a method causes the object to perform an action.


Triggering Methods

Think of methods as functionswhich is exactly what they are. When you invoke a method, code is executed. You can pass data to a method, and methods can return values. However, a method is neither required to accept parameters (data passed to it by the calling code) nor to return a value; many methods simply perform an action in code. Invoking (triggering) a method is similar to referencing the value of a property: You first reference the object's name, and then a dot, and then the method name as shown next:

{ObjectName}.{Method}


For example, to make the hypothetical Dog object Bruno bark using Visual C# code, you would use this line of code:

Bruno.Bark();


By the Way

Methods calls in Visual C# must always have parentheses. Sometimes they'll be empty, but at other times they'll contain data to pass to the method.


By the Way

Methods are generally used to perform an action using an object, such as saving or deleting a record in a database. Properties, on the other hand, are used to get and set attributes of the object. One way to tell in code whether a statement is a property reference or method call is that a method call will have a set of parentheses after it, as in frmAlbum.ShowDialog();.


Invoking methods is simple; the real skill lies in knowing what methods an object supports and when to use a particular method.

Understanding Method Dynamism

Properties and methods go hand in hand, and at times a particular method might become unavailable because of one or more property values. For example, if you were to set the NumberofLegs property on the Dog object Bruno equal to zero, the Walk() and Fetch() methods would obviously be inapplicable. If you were to set the NumberofLegs property back to four, you could then trigger the Walk() or Fetch() method again.




Sams Teach Yourself Microsoft Visual C# 2005 in 24 Hours, Complete Starter Kit
Sams Teach Yourself Visual C# 2005 in 24 Hours, Complete Starter Kit
ISBN: 0672327406
EAN: 2147483647
Year: N/A
Pages: 248
Authors: James Foxall

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net