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.
Jump into concepts and practice - no test required
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.
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.
name and a property Age that checks the value before setting it.public class Person { // Field public string name; // Property private int _age; public int Age { get { return _age; } set { if (value >= 0) _age = value; } } }
public class Car { // Auto-implemented property public string Model { get; set; } }
This program shows how a field and a property work. The property checks if the value is valid before setting it.
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}"); } }
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.
Fields store data directly inside a class.
Properties control how data is accessed or changed.
Properties help keep data safe and add flexibility.
field and a property in C#?Age with a private field in C#?age) and declared as private int age;.Age uses get and set to access the private field correctly.class Person {
private string name = "Alice";
public string Name {
get { return name; }
set { name = value; }
}
}
var p = new Person();
p.Name = "Bob";
Console.WriteLine(p.Name);p.Name = "Bob"; calls the set accessor, changing the private field name to "Bob".Console.WriteLine(p.Name); calls the get accessor, returning the updated value "Bob".class Car {
public int speed;
public int Speed {
get { return speed; }
set { speed = value; }
}
}
var c = new Car();
c.Speed = 50;
Console.WriteLine(c.speed);speed and property is Speed, so no naming conflict.c.speed directly bypasses the property, which can break encapsulation and safety.BankAccount where the Balance can be read publicly but only changed inside the class. Which is the best way to declare Balance?public decimal Balance { get; private set; } allows public reading but restricts setting to inside the class.