O'Reilly logo

C# 2010 All-in-One For Dummies® by Stephen R. Davis, Charles Sphar, Bill Sempf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 4. Let Me Say This about this

In This Chapter

  • How to pass an object to a method

  • Class methods versus instance methods

  • Understanding what this is

  • When you don't have this

  • When a class doesn't have a method that you need it to have

This chapter moves from the static methods that Chapter 3 in this minibook emphasizes to the nonstatic methods of a class. Static methods belong to the whole class, and nonstatic methods belong to each instance created from the class. Important differences exist between static and nonstatic class members.

Passing an Object to a Method

You pass object references as arguments to methods in the same way as you pass value-type variables, with one difference: You always pass objects by reference.

The following small program demonstrates how you pass objects — to methods, that is:

Note

// PassObject -- Demonstrate how to pass an object to a method.
using System;
namespace PassObject
{
  public class Student
  {
    public string name;
  }
  public class Program
  {
    public static void Main(string[] args)
    {
      Student student = new Student();
      // Set the name by accessing it directly.
      Console.WriteLine("The first time:");
      student.name = "Madeleine";
OutputName(student);
      // Change the name using a method.
      Console.WriteLine("After being modified:");
      SetName(student, "Willa");
      OutputName(student);
      // Wait for user to acknowledge.
      Console.WriteLine("Press Enter to terminate...");
      Console.Read();
    }
    // OutputName -- Output the student's name.
    public static void OutputName(Student student ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required