Learning C# Part 4: Classes and Objects

Written By: Kevin Jordan

- 14 Oct 2006 -
















Description: This series aims to take a beginning programmer to an intermediate level in C#. Topics covered in Part 4 include: classes and objects, accessibility and scope, methods, constructors, static class members, namespaces, and XML commenting.

  1. Classes and Objects
  2. The Stack and the Heap
  3. Defining a Class and Creating an Object
  4. Defining Accessibility and Scope
  5. Passing Parameters to a Method
  6. Overloading Methods
  7. Using Constructors
  8. Static Class Members
  9. Namespaces and XML Commenting
  10. Aww Man... Not Homework

Passing Parameters to a Method

I know I told you to ignore the CheckIfAccountExists method, and for the most part we will. But did you notice that we had tempAccount within the parenthesis? We were passing a parameter to the method. Think about if we called Console.Write("Print me"). We are actually passing a string (the words "Print me") to the method Write, in the Console class. See you were already using object oriented techniques and you didn't even know it.

When you pass a value type variable, the method receives a copy of the value that was assigned to the variable, so the original won't be affected. Here's how you would create a method that receives a value type variable.

class Client
{
        private string name;          // this is now private
 
        public void SetName(string firstName, string lastName)
        {
                name = firstName + " " + lastName;
        }
}
 
// While this is allowed, it is recommend that each class be
// in a seperate file. I'm doing this for simplicity
class WinForm
{
        static void Main()
        {
                // Create our new client
                Client newClient = new Client();
                newClient.SetName("Rox", "Steady");        // name is now "Rox Steady"         
        }
}

When the two strings "Rox", and "Steady" are passed as parameters, the method works on copies of those variables. This is called passing by value. Methods can only return a single value, but sometimes you want a method to modify or return multiple values. You can achieve this by passing the method a reference to the variable you want to modify.

When a value is passed by reference, the method receives a reference to the actual value or place in memory. Any changes that the method makes to the variable are actually made to the object that was passed. So, use this with utmost caution.

To declare a parameter is a reference parameter use the ref keyword. You must also use the ref keyword when you call the method.

class Client
{
        private decimal openingBalance = 0.0M;
 
        // Sets the balance to 0.0 on the object
        public void SetBalanceByRef(ref decimal newBalance)
        {
                newBalance = openingBalance;
        }
 
        public decimal SetBalanceByValue()
        {
                return openingBalance;
        }
}
 
// While this is allowed, it is recommend that each class be
// in a seperate file. I'm doing this for simplicity
class WinForm
{
        static void Main()
        {
                // This is where we'll store our balance from the methods
                decimal myBalance = 5.0M;
 
                // Create our new client
                Client newClient = new Client();
                newClient.SetBalanceByRef(ref myBalance);   // myBalance is now 0.0
                myBalance = 5.0M;                          // myBalance is now 5.0
                myBalance = newClient.SetBalanceByValue();       // myBalance is now 0.0
        }
}

While my example makes you think that passing by reference is completely useless, there are rare cases when it can be helpful. I try to avoid using pass by reference whenever possible.

Passing Reference Type Variables

Passing by reference can usually be avoided. Passing reference type variables usually cannot. When you pass a reference type variable to a method, the method can alter the actual values because it is operating on a reference to the same object on the heap. This example is going to be a little more complicated, we'll have three classes including our WinForm.

class Client
{
        public string name;   // We'll leave this public for simplicity
}
 
class Office
{
        public void GetNewClientName(Client newClient)
        {
                newClient.name = "Anonymous";
        }
}
 
class WinForm
{
        static void Main()
        {
                // Create a new office to do business in
                Office myOffice = new Office();
                
                // Create a new client for our business
                Client myClient = new Client();
 
                // Use a method from Office to figure out what we 
                // should name new clients
                myOffice.GetNewClientName(myClient);
                Console.Write(myClient.name);       // outputs "Anonymous"
        }
}

<< Previous

Next >>