DEV Community

1001binary
1001binary

Posted on

Protect class from disallowing changes to values outside in C#

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 :)

Top comments (0)