DEV Community

loading...

Protect class from disallowing changes to values outside in C#

1001binary
"Developer - Security Researcher" != None
・1 min read

The nature of OOP is to make program which are organized better into classes rather than functional programming. One of them is the class protection from disallowing any changes to values outside, once they are set. When writing code in OOP, it's significant to preserve its integrity.

The following is a small sample in C#:

Demo

public class Student
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

Fair enough :)

Production

The above code should be:

public class Student
{
   public Student(string firstName, string lastName)
   {
      this.FirstName = firstName;
      this.LastName = lastName;
   }
   public readonly string FirstName;
   public readonly string LastName;
}
Enter fullscreen mode Exit fullscreen mode

This disallows any changes to FirstName and LastName outside.

Hope you enjoy this post.

Happy coding :)

Discussion (0)