0
0
C Sharp (C#)programming~5 mins

Properties vs fields in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Properties and fields both store data in a class, but properties let you control how data is accessed or changed, while fields are simple storage.

When you want to keep data private but allow controlled access.
When you need to run extra code when data changes (like validation).
When you want to expose simple data without extra logic.
When you want to keep your class data safe from unwanted changes.
When you want to make your code easier to maintain and understand.
Syntax
C Sharp (C#)
class MyClass {
    // Field
    public int myField;

    // Property
    private int _myProperty;
    public int MyProperty {
        get { return _myProperty; }
        set { _myProperty = value; }
    }
}

A field is a variable inside a class.

A property looks like a field from outside but can run code when getting or setting.

Examples
This example shows a field name and a property Age that checks the value before setting it.
C Sharp (C#)
public class Person {
    // Field
    public string name;

    // Property
    private int _age;
    public int Age {
        get { return _age; }
        set {
            if (value >= 0) _age = value;
        }
    }
}
This is a simple property with automatic storage, no extra code needed.
C Sharp (C#)
public class Car {
    // Auto-implemented property
    public string Model { get; set; }
}
Sample Program

This program shows how a field and a property work. The property checks if the value is valid before setting it.

C Sharp (C#)
using System;

class Program {
    class Box {
        // Field
        public int length;

        // Property
        private int _width;
        public int Width {
            get { return _width; }
            set {
                if (value >= 0) _width = value;
                else Console.WriteLine("Width cannot be negative");
            }
        }
    }

    static void Main() {
        Box box = new Box();
        box.length = 10; // direct access to field
        box.Width = 5;   // uses property setter
        Console.WriteLine($"Length: {box.length}");
        Console.WriteLine($"Width: {box.Width}");

        box.Width = -3;  // tries to set invalid value
        Console.WriteLine($"Width after invalid set: {box.Width}");
    }
}
OutputSuccess
Important Notes

Fields are simple and fast but offer no control over data.

Properties can have logic to protect or modify data when accessed.

Use properties to keep your class safe and flexible.

Summary

Fields store data directly inside a class.

Properties control how data is accessed or changed.

Properties help keep data safe and add flexibility.