#513 – Some Familiar Methods that Accept Parameter Arrays

There are a number of methods in classes in the .NET Framework that accept parameter arrays, allowing you to pass a variable number of arguments to them.  Here are some examples:

String.Format:

int ft = 5;
int inches = 2;
string eyeColor = "blue";
string exclamation = "oh";
// string string.Format(string format, params object[] args)
string lyric = string.Format("{0} ft {1}, eyes of {2}; but {3} what those {0} foot could do", ft, inches, eyeColor, exclamation);

Console.WriteLine:

            string[] favs = {"Kittens", "Mittens", "Packages", "Tractors", "Streudel"};
            // void Console.WriteLine(string format, params object[] args)
            Console.WriteLine("Fav things: {0}, {1}, {2}, {3}, {4}", favs);

(Note: Console.WriteLine has an overload that accepts four object parameters after the format string, so the version with the parameter array doesn’t kick in until you use at least five parameters).

Path.Combine:

// string Path.Combine(params string[] paths)
string path = Path.Combine("D:\\", "Sean", "Notes", "WCF");

#512 – Two Ways to Pass Data to a Method that Takes a Parameter Array

Defining a parameter array using the params keyword allows you to pass a variable number of arguments to a method.

public void PerformCommands(params string[] commands)

You can pass a variable number of arguments to a method that has a parameter array.

            kirby.PerformCommands("Sit", "Stay", "Beg");

You can also just pass an array of the proper type.

            string[] tricks = new string[] {"Roll over", "Weave"};

            kirby.PerformCommands(tricks);

#511 – Rules for Using Parameter Arrays

You can use the params keyword when declaring a method to define a parameter array, allowing you to pass a variable number of parameters to the method.

public void PerformCommands(params string[] commandList)
{
    foreach (string command in commandList)
        Console.WriteLine("Ok, I'm doing [{0}]", command);
}

You can then pass any number of parameters to the method.  Every parameter that you specify is added to the single array that is passed to the method.

kirby.PerformCommands(new string[] { "Sit", "Stay", "Come" });

When using the params keyword:

  • You can only define one parameter array for a given method
  • The parameter must be the last parameter specified
  • The array must be a single-dimensional array
  • You can’t use the ref or out modifiers on the parameter array or on any of the arguments
  • Each argument must be implicitly convertible to the type of the array’s elements

#354 – Correct Overloaded Method Is Automatically Called

When you have several overloaded methods in a class, the compiler will call the correct method, based on the type of the arguments passed to the method.

When you overload a method, you define several methods in a class with the same name, but different parameters.

    public class Dog
    {
        // General bark
        public void Bark()
        {
            Console.WriteLine("Woof");
        }

        // Specific bark
        public void Bark(string barkSound)
        {
            Console.WriteLine(barkSound);
        }

        // Repeated barking
        public void Bark(int numBarks)
        {
            for (int i = 1; i <= numBarks; i++)
                Console.WriteLine("Woof #{0}", i);
        }
    }

The compiler will automatically figure out which method to call, based on the arguments that you pass in.

            Dog jack = new Dog("Jack", 15);

            jack.Bark();           // General bark
            jack.Bark(5);          // Repeated barking
            jack.Bark("Rowwwwf");  // Specific bark

#341 – Defining and Using Local Variables

You can define variables within a method.  These are known as local variables.  The variables’ values can be read and written while the body of the method is executing.

The Dog.Bark method below defines two local variables–formalName and barkPhrase.

    public class Dog
    {
        public string Name { get; set; }
        public string BarkSound { get; set; }

        public void Bark()
        {
            string formalName = string.Format("Sir {0}", Name);
            string barkPhrase = string.Format("{0} {0}!", BarkSound);

            Console.WriteLine("{0} says {1}", formalName, barkPhrase);
        }
    }

Local variables can be initialized when they are declared, or they can be set to a value later.  Since C# requires definite assignment, they must be given a value before they are read.

 

#340 – Use the params Keyword to Pass a Variable Number of Arguments

When you define a method in a class, the parameters of the method normally dictate the exact number of arguments that you can pass to the method.  There are times, however, when you might want to pass a variable number of parameters to a method.

You could pass a variable number of parameters to a method by using an array.

        public void PerformCommands(string[] commandList)
        {
            foreach (string command in commandList)
                Console.WriteLine("Ok, I'm doing [{0}]", command);
        }

You’d call this method by creating a new instance of an array.

            kirby.PerformCommands(new string[] { "Sit", "Stay", "Come" });

To simplify things, you can use the params keyword in the method definition.  This allows passing the elements of the array as individual arguments.

        public void PerformCommands(params string[] commandList)

This makes calling the method a little cleaner.

            kirby.PerformCommands("Sit", "Stay", "Come", "Fetch");

#284 – Static Methods Can Call Instance Methods

Static methods can call instance methods in a class–provided that they have access to a reference to an instance of the class.

In the example below, we have a static method of the Dog class that dumps out a bunch of information about every Dog instance in a collection of dogs passed to it.

        public static void ListDogs(List<Dog> dogList, Cat cat)
        {
            foreach (Dog d in dogList)
            {
                string likes = d.LikesCat(cat) ? "Yes" : "No";

                Console.WriteLine("{0}: {1} yrs old.  Motto is [{2}]. Likes {3}? {4}",
                    d.Name,
                    d.Age,
                    d.Motto,
                    cat.Name,
                    likes);
            }
        }

Note that the static Dog method can also call an instance method of the Cat class.

Here’s how we might call this method:

            List<Dog> dogs = new List<Dog>();

            dogs.Add(new Dog("Kirby", 14, "Chase balls"));
            dogs.Add(new Dog("Jack", 17, "Lounge around house"));
            dogs.Add(new Dog("Ruby", 1, "Stare out window"));

            Cat morris = new Cat("Morris");

            Dog.ListDogs(dogs, morris);

Output:

#283 – Instance Methods Can Call Static Methods

Instance methods in a class can access static data or call static methods.  The instance method accesses static data or methods in the same way that other code does–by using the class name to qualify the data or method name.

Here’s an example, where the Dog.Bark instance method makes use of the private static Dog.FormatTheCreed method:

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Private static method to format our Dog creed
        private static string FormatTheCreed()
        {
            return string.Format("As dogs, we believe: {0}", Dog.Creed);
        }

        // Instance method, in which a Dog barks
        public void Bark()
        {
            // Dump out my name and the universal Dog creed.
            Console.WriteLine("{0}: 'Woof'!  (Creed: [{1}])", this.Name, Dog.FormatTheCreed());
        }

Calling the Bark method:

            // Set static property
            Dog.Creed = "We serve man";

            Dog kirby = new Dog("Kirby");
            kirby.Bark();

#282 – Creating Private Static Methods

Like instance methods, static methods can be public or private.  A private static method is a method that works with the class’ static data, but is not visible from outside the class.

Below is an example of a private static method.  Note that it’s making use of some public static data.  It could also work with private static data.

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Public static method, to recite our creed
        public static void RepeatYourCreed(int numRepeats)
        {
            string creed = FormatTheCreed();

            for (int i = 0; i < numRepeats; i++)
                Console.WriteLine(creed);
        }

        // Private method to format our Dog creed
        private static string FormatTheCreed()
        {
            return string.Format("As dogs, we believe: {0}", Dog.Creed);
        }

We can call the public static method that makes use of this private method:

            // Set static property
            Dog.Creed = "We serve man";

            // Call static method
            Dog.RepeatYourCreed(3);

#281 – Declaring and Using Static Methods in a Class

A static method in a class is similar to an instance method, except that it acts upon the class’ static data–fields and properties–rather than on the instance data stored with a single instance of the class.

There is only one copy of each static data item, no matter how many instances of the class exist.

Here’s an example of defining a static method in a class.

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Static method acts on static data
        public static void RepeatYourCreed(int numRepeats)
        {
            for (int i = 0; i < numRepeats; i++)
                Console.WriteLine("My creed is: {0}", Creed);
        }

To call a static method, you just prefix the method with the name of the class (rather than with a reference to an instance of the class).

            // Set static property
            Dog.Creed = "We serve man";

            // Call static method
            Dog.RepeatYourCreed(3);

Follow

Get every new post delivered to your Inbox.

Join 37 other followers