csharp / beginner
Snippet
Secure Data Access via Properties
Encapsulation protects sensitive data by making fields private and controlling access through methods or properties.
snippet.cs
csharp
1
2
3
4
5
6
7
8
public class UserProfile {private string _password;public string Username { get; set; }public void SetPassword(string secret) {if (!string.IsNullOrEmpty(secret)) _password = secret;}}
Breakdown
1
private string _password;
Hides the data from direct access outside the class.
2
public string Username { get; set; }
An auto-property that provides controlled public access to a value.