C#C
C#3y ago
cow

Is there a way to ensure a function can't modify a parameter?

I often want to pass objects or values into a function, and make sure the function cannot change it... is it possible?

Example scenario:
public void UpdateUserAge() {
    var user = _dbContext.Users.Find(4);
    user.Age = 111;
    
    // How to make sure WriteUserLog can not modify user?
    WriteUserLog(user);
    
    _dbContext.SaveChanges()
]


private void WriteUserLog(UserEntity user) //can this parameter be made readonly somehow?
{
    user.Name = "Shouldnt be able to change this";
    Console.WriteLine($"User {user.Age} was changed")
}
Was this page helpful?