tags:

views:

330

answers:

4

I've always wanted to be able to use the line below but the C# compiler won't let me. To me it seems obvious and unambiguos as to what I want.

myString.Trim({'[', ']'});

I can acheive my goal using:

myString.Trim(new char[]{'[', ']'});

So I don't die wondering is there any other way to do it that is closer to the first approach?

+8  A: 

The string.Trim(...) method actually takes a params argument, so, why do you not just call:

myString.Trim('[', ']');
jerryjvl
In case you've never worked with 'params' before, it's well worth looking up in the IDE help...
jerryjvl
I always forget about the single quotes to indicate chars. Subtle yet significant.
Loki Stormbringer
+3  A: 

This will work too ...

myString.Trim( '[',']' );

Note the params declaration in the defition of Trim, it let's you pass as many arguments as you want and takes them as an array.

JP Alioto
+3  A: 

You could also try this:

myString.Trim("[]".ToCharArray());
Loki Stormbringer
+5  A: 

Others have concentrated on the specific example (and using the fact that it's a parameter array is the way to go), but you may be interested in C# 3's implicit typing. You could have written:

myString.Trim(new[] {'[', ']'});

Not quite as compact as you were after, as you still need to express the concept of "I want to create an array" unless you're writing a variable initializer, but the type of the array is inferred from the contents.

The big use case for this is anonymous types:

var skeets = new[] {
   new { Name="Jon", Age=32 },
   new { Name="Holly", Age=33 },
   new { Name="Tom", Age=5 },
   new { Name="Robin", Age=3 },
   new { Name="William", Age=3 }
};

Here you couldn't write the name of the type, because it doesn't have a name (that's expressible in C#).

One other point to make about your specific example - if you're going to use this frequently (i.e. call the Trim method often) you may want to avoid creating a new array each time anyway:

private static readonly char[] SquareBrackets = {'[', ']'};

public void Whatever() {
    ...
    foo = myString.Trim(SquareBrackets);
    ...
}
Jon Skeet
In cases where there is no 'params' to work with it's always possible to put an alternative together with extension methods, but I'm not sure if that would be classified 'cheating' in the context of this question ;)
jerryjvl
Why did the C# designers decide "new[]" is needed? Can syntax of the for { ..., ..., ...} ever be used to declare anything but an array?
sipwiz
Anonymous types: new { foo, bar, baz } is valid. Likewise collection initializers when they're just adding to an existing collection. I think it makes it clearer what you're doing - you need less context to understand what the braces are there for.
Jon Skeet