Properties Vs Fields In C#

Fields are normal variable members of a class. Properties are an abstraction to get and set their values. In this quick tutorial, you will understand the difference between them, and which one to use.

Fields

Fields are normal variable members of a class. Generally, you should declare your fields as private, then use Properties to get and set their values. By this way you won’t affect their values them directly. This is common case practice since having public members violates the Encapsulation concept in OOP.

public class Student
{
private int _id;
private string _name;
}

Properties

They are actually special methods called “accessors”. Properties are called accessors because they offer a way to get and set a field if you have a private field. They have two codes inside; set{}; and get{}; called “property accessors”.

public class Student
{
private int _id;
private string _name;
        public int Id { get { return _id; } set { _id = value; } }
public string Name { get { return _name; } set { _name = value; } }
}

“value” is a keyword, It refers to the assigned value, It’s like a parameter for the set method, The final code snippet will make it more obvious.

Properties can be used to read only or write only other fields. This could be done by declaring only either get{} or set{}. Also they can have access modifiers, like private, so you can only get or set their values inside their class.

In Java, We need to declare getters and setters methods, But, In C#, You can defined a property for each field.

Putting All Together

class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.Id = 41134; // Now, keyword "value" of Id property has the value of 41134
stu.Name = "Stephan"; // "value" of Name property has the value of "Stephan"
          // Console.WriteLine(stu._id); This is an Error!.
           Console.WriteLine(stu.Id);
Console.WriteLine(stu.Name);
           // Or you can use a method to trigger the private fields.
stu.printValues();
}
}
public class Student
{
private int _id;
private string _name;

public int Id { get { return _id; } set { _id = value; } }
public string Name { get { return _name; } set { _name = value; } }
       public void printValues(){
Console.WriteLine(this._id);
Console.WriteLine(this._name);
}
}

You have reached the end of this tutorial!, revise the code snippets above, and share it if you find it useful.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.