-1

I am a VBA developer and new to C# Below is my Employee Class :

class Employee
{
   public string name;

   public Employee()
    {
       age = 0;
    }

    public void setName(string newName)
    {
        name = newName;
    }  
}

When I create an object of my Employeeclass, I can either use the method provided to set the value of name

Employee E1 = new Employee();
E1.setName("Name 1");

or I can set the name directly.

Employee E1 = new Employee();
E1.name = "Name 1"

The whole point is How can I stop users to set the value of my fields directly / without calling my method , If you could please tell me how can I set the values of my class fields efficiently.

PankajKushwaha
  • 878
  • 2
  • 11
  • 25
  • 2
    by making the fields private. [Access Modifiers (C# Programming Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers) / [private (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private) – Nkosi Nov 25 '17 at 11:16
  • Make your fields/properties `private` instead of public, so that other functions outside the class can't access them – Shobi Nov 25 '17 at 11:17

3 Answers3

2

Just use properties instead of (public) fields.

public class Employee
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            // Your setter-code here. Validation and stuff like that
            _name = value;
        }
    }
}
Michael
  • 1,931
  • 2
  • 8
  • 22
2

You would like to use a public property and make the field private like below. You don't need a separate setter method likewise you are doing

class Employee
{
   private string name;

   public Employee()
    {
       age = 0;
    }

    public string Name
    {
      get {return name; }   
      set { name = value; }
    }  
}
Rahul
  • 76,197
  • 13
  • 71
  • 125
-1

You should define private member.

class Employee
{
   private string name;

    public void setName(string newName)
    {
        name = newName;
    }  
}

NOTE: Private members of a class can only be accessed within class definition while public members can be accessed outside class by using its object.

Or, simply use Properties as,

class Employee
{
    private string name;
    public string Name
    {
        get { return name; }
        set { name = value; }
    }
}

Using proerty, you can set Name as,

  Employee emp = new Employee();
  emp.Name = "suman";
Er Suman G
  • 581
  • 5
  • 12