What is a property in C#?

Experience Level: Junior
Tags: C#

Answer

In C# a property is used to store a value to an object or retrieve a value from an object. You may want to store multiple different values to an object. In such case you would define one property for each value. Each property would have its data type that defines what type of value can be stored to the property or retrieved from the property.

Imagine you would like to have an object that represents a person. By what data values would you want to describe a person? Maybe Height? Weight? Age? Name? Eye color? Date of birth? All these values could be properties.

Example
public class Person 
{
  public float Height { get; set; }
  public float Weight { get; set; }
  public int Age { get; set; }
  public string Name { get; set; }
  public Color EyeColor { get; set; }
  public DateTime DateOfBirth { get; set; }
}
Related C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself