© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
24 replies
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")
}
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")
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ is there a way for a method to have interchangeable parameter?
C#CC# / help
3y ago
Ensure there is always a value in NumericUpDown?
C#CC# / help
8mo ago
Is there a memset function?
C#CC# / help
2mo ago
❔ Optional function parameter
C#CC# / help
3y ago