Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an entire Class as a Parameter - Good practice?

Suppose a class called "Place" stores locations and relevant details:

class Place
{
    string Name;
    string Location;
    // etc...
}

Later on we populate the name and details of up to 80 different towns. So we store these Towns numerically in an array:

class Setup
{
    public static GetTowns
    {
        for (int i = 1; i <= numberOfTowns; i++)
        {
            Town[i] = new Place(name, location);
        }
        // more code...
    }
    // more methods...
}

To access a specific Town and its data, we pass the Town itself as a parameter and receive it:

public static void DescribeTown(Place Town)
{
    // example method from some other class
    Console.WriteLine("Shipping to {0}.", Town.Name);
}

Other methods need access multiple towns, or all of them. Then we can pass in the entire Town array as a parameter:

public static void ListAllTowns(Place[] Town)
{
    Console.WriteLine("Our Beloved Clients:");
    foreach (Place here in Town)
    {
        Console.WriteLine("{0} in {1}", here.Name, here.Location);
        // Various other operations requiring info about the Towns
    }
}

The Complete Reference, C# 2.0, states the following

Parameters are variables that receive the value of the arguments passed into the method when it is called.

This seems to say every instance of a class, and all data involved, is being passed into ListAllTowns each time it is called. That sounds wasteful to me, but is it?

(This example is heavily simplified for proof-of-concept reasons, but methods require read/write permissions and comparison between multiple towns.)

like image 641
4444 Avatar asked Aug 21 '12 16:08

4444


1 Answers

There's nothing wasteful about it. You're not passing a copy of all of the items, you're simply creating an array and then passing a reference to that array to the ListAllTowns method (arrays are reference types).

You're doing things (one of) the right way(s).

like image 173
Justin Niessner Avatar answered Sep 23 '22 00:09

Justin Niessner