I have a class LoginManager which has a private field currentUser and a public property CurrentUser to not allow myself to accidentally change the value of CurrentUser from outside the LoginManager class.
CurrentUser is { get; } only but I can still change properties in the underlying currentUser which is private.
eg.
Console.WriteLine(loginManager.CurrentUser.ClockedIn.ToString()); // true
loginManager.CurrentUser.ClockedIn = false;
Console.WriteLine(loginManager.CurrentUser.ClockedIn.ToString()); // false
loginManager.CurrentUser.ClockedIn = true;
Console.WriteLine(loginManager.CurrentUser.ClockedIn.ToString()); // true
LoginManager.cs
public class LoginManager
{
private User? currentUser { get; set; }
private readonly ApplicationDbContext dbContext;
public event EventHandler CurrentUserChanged;
public User? CurrentUser
{
get { return currentUser; }
}
//...
}
User.cs
public class User
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool ClockedIn { get; set; }
}
I want it so that I can't change CurrentUser from outside the LoginManager class. Could anybody please point me in the right direction?
I think I see the problem, the private CurrentUser instances get and set properties are exposed outside the class since those member variables are public in scope.
Why not make the User properties private?
public class User
{
private Guid Id { get; set; }
private string Name { get; set; }
private string Username { get; set; }
private string Password { get; set; }
private bool ClockedIn { get; set; }
}
Or if you need to get the properties mark private set:
public class User
{
public Guid Id { get; private set; }
public string Name { get; private set; }
public string Username { get; private set; }
public string Password { get; private set; }
public bool ClockedIn { get; private set; }
}
Or explicitly make them readonly so they can only be initialized in the Constructor:
public class User
{
public readonly Guid Id { get; private set; }
public readonly string Name { get; private set; }
public readonly string Username { get; private set; }
public readonly string Password { get; private set; }
public readonly bool ClockedIn { get; private set; }
public User(Guid Id, string Name, string Username, string Password, bool ClockedIn)
{
this.Id = Id;
this.Name = NameName;
this.Username = Username;
this.Password = Password;
this.ClockedIn = ClockedIn;
}
}