Convert type string to object type

I am new to C #. I need to show the full username in the console application, but I keep getting this error

Cannot implicitly convert type 'string' to 'UserCustomerNotes.User'

My code works when I use only return user, but all that it shows in the application is "UserCustomerNotes.User" and I need to show the full username. Someone can 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;
}
+3
source share
4 answers

Your code:

public static User FindUser(User[] users, int noteid)
{       
    foreach (User user in users)                
        if (user.ID == noteid) return user.FullName;
    return null;
}

string ( user.FullName), , User. ( FindUser:

var ArrayOfUsersToSearch = GetAnArrayOfUserFromSomewhere();
var noteId = 3; // Or whatever value you want to use
var myUserToFind = FindUser(ArrayOfUsersToSearch, noteId);

Console.WriteLine("The users full name is: {0}", 
        myUserToFind != null ? myUserToFind.FullName : "Not Found");

FindUser :

public static User FindUser(User[] users, int noteid)
{       
    foreach (User user in users)                
        if (user.ID == noteid) return user;
    return null;
}

, "UserCustomerNotes.User" User :

Console.WriteLine(FindUser(users, noteId));

// instead of

Console.WriteLine(FinderUser(users, noteId).FullName);

UserCustomerNotes.User "ToString", - , , , Console.WriteLine User , . , "" .

. Console.WriteLine("The users full name is: {0}", myUserToFind != null ? myUserToFind.FullName : "Not Found");, null, , , , .

, , :

foreach(var x in y)
    do something;

"", , { } :

foreach (User user in users)                
{
    if (user.ID == noteid) 
    {
        return user.FullName;
    }
}
return null;
+3

, typeUser, , - :

public static **string** FindUser(User[] users, int noteid)

, :

if (user.ID == noteid) return user;
+9

, User. string.

public static string FindUser(User[] users, int noteid)
{       
    foreach (User user in users)                
        if (user.ID == noteid) return user.FullName;
    return null;
}
+1

ToString User:

public override string ToString()
{
    return FullName;
}

Console.WriteLine("User name {0}", user);
0

Source: https://habr.com/ru/post/1761715/


All Articles