This returns an array with only one element and thus throws an exception. But it works when I omit StringSplitOptions.TrimEntries.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("a-b".Split('+', '-', StringSplitOptions.TrimEntries)[1]);
}
}
Could it be that it is picking this overload:
public string[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None)
But since when in C# is char
compatible with int
?
This returns an array with only one element and thus throws an exception. But it works when I omit StringSplitOptions.TrimEntries.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("a-b".Split('+', '-', StringSplitOptions.TrimEntries)[1]);
}
}
Could it be that it is picking this overload:
public string[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None)
But since when in C# is char
compatible with int
?
2 Answers
Reset to default 6since when in c# char is compatible with int?
char
has been implicitly convertible to int
in C# since version 1.
Could it be that it is picking this overload: ...
It has to be; it is the only overload that fits the method call. If this overload didn't exist, the code wouldn't compile.
I presume you expected this overload instead:
public string[] Split (char[]? separator, StringSplitOptions options)
However, this option is not compatible with the provided arguments, because the params
modifier is not included as part of the signature (params
must come last in the argument list). Therefore the '+', '-'
portion of the method call cannot be interpreted as an array here. Nor is there an overload using IEnumerable<char>
that could be chosen.
If you wish to use this other overload, you must ensure the array is fully-constructed before the method call resolves.
Yes, a char
is implicitly convertible to int
Demo
"a-b".Split(['+', '-'], StringSplitOptions.TrimEntries)[1]
should do what is needed (if I understand correctly the goal). – Guru Stron Commented yesterdayparams
) and then after that if pass a different type of parameter that will be the exact issue you are facing. i.e. without looking at the docs I know your code isn't going to work since you are passingStringSplitOptions.TrimEntries
after the params. – mjwills Commented yesterday