C#
C#

help

Root Question Message

rallez
rallez2/13/2023
✅ Give object default values (destroy?)

Hi I have a program which after sign in assignes object user some values. While sign out i need to delete/destroy or set as default those vaules.
public class User
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public List<Character> Characters { get; set; }

    public User(string username, int userid)
    {
        Username = username;
        UserId = userid;
        Characters = new List<Character>();
    }

    ~User()
    {
        Username = "";
        UserId = default;
        Characters = new List<Character>();;
    }
}

I've heard about deconstructor but i dont know how to use them to be honest. Please help me
AntonC
AntonC2/13/2023
forget about the deconstructor
AntonC
AntonC2/13/2023
either set the whole user to null, which would make more sense, or make a method that resets them
AntonC
AntonC2/13/2023
you have to do that manually
AntonC
AntonC2/13/2023
if it were a struct tho, you could've done this = default
rallez
rallez2/13/2023
okay but earlier in my code im creating new User user
rallez
rallez2/13/2023
it won't give me an error?
AntonC
AntonC2/13/2023
idk I don't have your code
rallez
rallez2/13/2023
a ihave a login function that creates user object
rallez
rallez2/13/2023
now i want to create a function that log out
rallez
rallez2/13/2023
no user can sign in, log out and the again sign in for example
phaseshift
phaseshift2/13/2023
that is business logic, nothing to do with destroying or destructing a user instance
thinker227
thinker2272/13/2023
What this would do is when the instance itself is garbage collected, the destructor is run, which would make it completely useless.
rallez
rallez2/13/2023
so can I do that and it will be completly fine?
User user = new User(providedUsername, Data.TempUserId);
// HERE SOME CODE
User user = new User(providedUsername, Data.TempUserId);
rallez
rallez2/13/2023
and will it overwrite it right?
phaseshift
phaseshift2/13/2023
well, no. 'user' is the same variable name. But apart from that, you have a valid duplicate
phaseshift
phaseshift2/13/2023
its not overwriting anything
phaseshift
phaseshift2/13/2023
User user = new User(providedUsername, Data.TempUserId);
// HERE SOME CODE
user = new User(providedUsername, Data.TempUserId); // re-assign the 'user' variable.
phaseshift
phaseshift2/13/2023
The first User instance will get GC'd at some point
thinker227
thinker2272/13/2023
"Garbage collected" or "GC'd" is when an object has no references throughout the entire program. It's inaccessible, gone, discarded. At that point, the destructor might be run, before the memory is freed entirely, but you can't really do anything of value at that point.
thinker227
thinker2272/13/2023
anyway, as already stated, destructors are not the right tool here.
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy