Home > Articles > Software Development & Management > Object Technology

  • Print
  • + Share This
This chapter is from the book

Creating Methods

We were introduced to creating methods in Chapter 2, "Basic C# Programming," but there are a few more considerations to add. First, as we saw in ch03_01.cs, Listing 3.1, methods can be declared with access modifiers, and that's important when you're creating objects. Declaring a method public makes it accessible outside an object, for example, whereas declaring it private locks it away inside the object.

Now that we're thinking in terms of objects and methods, it's also important to discuss the this keyword. This keyword works the same in C# as it does in C++, and it refers to the current object in which your code is executing. For example, say you're writing code to set up a button that appears in a window and you want to pass the whole button to a method named ColorMe. You can do that by passing the this keyword to that method:

public class Button
{
 public void SetUp()
 {
  ColorMe(this);
 }
}

Another use for the this keyword is to refer to a field in the current object. In this example, the method SetMessage is passed a parameter named message, which it is supposed to store in the field of the same name in the current object. To avoid confusion, you can refer to the field named message in the current object as this.message, like this:

private string message;

public SetMessage(string message) 
{
 this.message = message;
}

This example also illustrates another use for methods in classes: creating accessor methods. In this case, access to the private message field is restricted. From outside the current object, you have to call the SetMessage method to assign data to this field. Restricting access to an object's internal data is usually a wise thing to do, so much so that accessor methods have been formalized in C# into properties.

  • + Share This
  • 🔖 Save To Your Account