Set string to 1st element in string[]

I have a method which returna a string array. Is it possible to set a string value to the first element in that array without first declaring the string array e.g.:

myString = getStringArrayMethod(someValue)[0]



Make getStringArrayMethod static?

Why would you want to do that? The array could be null or empty. Perhaps you can tell us more, about what you need?

myString = getStringArrayMethod(someValue)!=null && getStringArrayMethod(someValue).Length>0 ? getStringArrayMethod(someValue)[0] : “”;

then again setting it on a variable would be best.

How about writing an extension method for this?

public static class StringExtensions
    public static string FirstOrDefault(this string source)
        return source.ToCharArray().FirstOrDefault().ToString();

And use it like this:

someValue = someValue.FirstOrDefault();

Linq.FirstOrDefault is available on a string due to an Array inheriting from IEnumerable so you don’t need to write your own

Snap! I never noticed. LOL! Thanks D.