November 25, 2007

Using the Params keyword

string[] ReplaceInStrings(char oldchar, char newchar, params string[] src)
    string[] res = new string[src.Length];
    int ix = 0;
    foreach (string targ in src)
        res[ix++] = targ.Replace(oldchar, newchar);
    return res;
The nice thing about the use of the 'params' keyword is that it can take an array parameter directly or a series of the specified type. It can even work with no parameters of the specified type. The following code demonstrates this behaviour
private void ParamsTest()
    string[] res;
    string[] strings = new string[] { "Some_string", "Another_string"};
    // Pass an array directly
    res = ReplaceInStrings('_', ' ', strings); 
    // Pass a series of objects of the specified type, this is automatically
    // converted to an array
    res = ReplaceInStrings('_', ' ', "This_string", "That_string", "Unchanged"); 
    // Pass a single object of the specified type
    res = ReplaceInStrings('_', ' ', "A_Single_string"); 
    // Pass NO objects of the specified type!
    // This still works an empty array is passed into the routine
    res = ReplaceInStrings('_', ' '); 

can it be used on a remoting interface?

No comments: