C # How to return the first letter of a string as a char in a method?


I'm making an assignment in my class, which question is: Create a method, call it A, and make it return the first letter in a string.

This is my code:

    String f = "flying";
    String str = A(f);



public static string A(string s)
    string first = s.Substring(0, 1);
    return first;

But it's not acceptable, as I'm returning a string rather than a char. I can't find anywhere how to return the letter 'f' in flying as a char, and I would appreciate some help.

basically a string is an array of chars, so if you would treat it like one and access the first position using the [ ] operator:

char c = s[0];

You will get a char.

This will of course lead to problems if your string is either null or empty. So you really should check for that cases:

char c = !String.IsNullOrWhiteSpace(s) ? : s[0] :  ' ';

another possibility would be simply to convert it to a char using the Convert.ToChar method. Here again a check would be necessary

public static char A(string s)
    return !String.IsNullOrWhiteSpace(s) ? Convert.ToChar(s.Substring(0, 1)) : ' ';

Sidenote: If you wonder what the ? is about have a look on the ?: Operator (C# Reference)

As pointed out by Ehsan Sajjad using First should suffice:

return !String.IsNullOrWhiteSpace(s) ? s.First() : ' ';