George
George

Reputation: 1974

Is there an easier way of passing a group of variables as an array

What I'm trying to do is to write a dedicated method for my StreamWriter instance, rather than make use of it at random points in the program. This localises the places where the class is called, as there are some bugs with the current way it's done.

Here is what I have at the moment:

public static void Write(string[] stringsToWrite) {

    writer = new StreamWriter(stream);

    writer.Write("hello");

    foreach (string stringToWrite in stringsToWrite) {
        writer.Write(" " + stringToWrite + " ");
    }

    writer.Flush();
}

Note: stream is an instance of a TcpClient

With this I'm able to pass an array of variables to write, but I can't use the same method calls as with the existing method:

writer.WriteLine("hello {0} {1} {2}", variable1, variable2, variable 3);
writer.Flush();

It would be great if I was able to pass x number of variables to the method and for the loop to write each of them in this fashion, however optional parameters in .NET don't arrive till v4.0 which is still in beta.

Any ideas?

Upvotes: 3

Views: 279

Answers (5)

Joey
Joey

Reputation: 354426

You can take a look at the params keyword:

public static void Write(params string[] stringsToWrite) {
    ...    

    foreach (string stringToWrite in stringsToWrite) {
        writer.Write(" " + stringToWrite + " ");
    }

    ...
}

Usage would be exactly what you want, then.

Upvotes: 8

Marc Gravell
Marc Gravell

Reputation: 1062630

params (already mentioned) is the obvious answer in most cases. Note that you might also consider alternatives, for example:

static void Main() {
    string s = Format("You are {age} years old and your last name is {name} ",
        new {age = 18, name = "Foo"});
}

As shown here and discussed more here.

Upvotes: 3

flq
flq

Reputation: 22839

Use the params keyword on your method:

public static void Write(params string[] stringsToWrite) {

Then you can say

Write("Hello", "There")

You can still pass in an ordinary array, as much as WriteLine would accept one.

Upvotes: 3

stevehipwell
stevehipwell

Reputation: 57488

Use a param array!

public void Write(params string[] oStrings)
{
}

Upvotes: 1

Joren
Joren

Reputation: 14746

Use params:

public static void Write(params string[] stringsToWrite) {
    ... // your code here
}

Call as Write(a, b, c), which would be equivalent to Write(new string[] {a, b, c}).

Upvotes: 2

Related Questions