Search code examples
c#encapsulation

How to prevent the values of properties initialized by the constructor from being overwritten


I am new to programming and am trying to prevent the Program class from overwriting the values of the properties that were initialized by the constructor of the Person class

Here is my code: please see the comments highlighting what I am trying to achieve

using System;

namespace Test
{
    class Program
    {
        class Person
        {
            public string FName { get; set; }
            public string LName { get; set; }

            public Person(string fName, string lName)
            {
                FName = fName;
                LName = lName;
            }

            public override string ToString()
            {
                return FName + " " + LName;
            }

        }

        static void Main()
        {
            Person person = new Person("Adam", "Lake");
            person.FName = "Fabio";      // I want to prevent this 
            person.LName = "Scagliola";  // I want to prevent this 
            Console.WriteLine(person);
        }

    }
}


Solution

  • Change you properties FirstName and LastName to Read-only Auto-Implemented Properties

    public string FirstName { get; }
    public string LastName { get; }
    

    It means that you can only set the value from the Person constructor