If you want to check for valid numbewrs, then you are probably best off doing a trial conversion to the actual datatype you are expecting.
So if you are expecting integer values in string form then use the int.TryParse method:
public string BuildList(object[] input)
{
StringBuilder result = new StringBuilder();
foreach (object o in input)
{
string s = o as string;
if (s != null)
{
int i;
if (int.TryParse(s, out i))
{
result.AppendFormat("{0}, ", s);
continue;
}
}
return "Error";
}
return result.ToString();
}
Note that I have changed your code quite a bit - some of it to make your code compile (adding the return at the end), some to make it clearer (changing the
for
loop to a
foreach
) and some to make it more efficient (using a StringBuilder rather than concatenating strings). I also sorted out the indentation for you, so it is easier to read...
"hallo originalGriff thank you so much for your response the question is I have to handle the nullreference exception an the error input example"test" I do not know the type of the input"
Try this:
public string BuildList(object[] input)
{
StringBuilder result = new StringBuilder();
foreach (object o in input)
{
if (o != null)
{
string s = o.ToString();
if (s != null)
{
int i;
if (int.TryParse(s, out i))
{
result.AppendFormat("{0}, ", s);
continue;
}
}
}
return "Error";
}
return result.ToString();
}