I am new to C#. I need to show a users fullname in a console application, but I keep getting this error
Cannot implicitly convert type ‘string’ to ‘UserCustomerNotes.User’
My code works when I only use return user but all that it shows in the app then is “UserCustomerNotes.User” and I need to show the fullname of the user. Can anyone please help. Here is my code:
public static User FindUser(User[] users, int noteid)
{
foreach (User user in users)
if (user.ID == noteid) return user.FullName;
return null;
}
Your code:
Is expecting to return a
stringobject (theuser.FullNamevalue) when it succeeds in finding one, whereas the return type you’ve declared for your method isUser. What you should do is this (where you’re currently callingFindUser:And change the code in your
FindUsermethod to be:The reason you see “UserCustomerNotes.User” output when you return
userfrom your method is this:Because the return type is
UserCustomerNotes.Userand it doesn’t have an override of “ToString” to specify anything different, the default value that is given when Console.WriteLine asks yourUserobject for its textual equivalent is its name. This explains why you see the “odd” output from your code currently.It’s also worth mentioning, but unrelated to the question itself, that the format:
Can be more prone to “breaking” if changes are made further down the line than if you explicitly call out the
{and}around each statement block: