How can you assign a value to a property in C#?

Experience Level: Junior
Tags: C#

Answer

In order to assign a value to a property of an object that is stored in a variable, just type a name of that variable, dot character, name of the property, equals sign, a value that you want to assign and a semicolon in the end.

In the example below, the property VolumeLevel will be set to value 10. Note that the property VolumeLevel belongs to object that is stored in the variable myRadio. The object was created based on the class Radio. We are saying the object is of type Radio.

Example
public class Program 
{
  public static void Main() {
    var myRadio = new Radio();
	myRadio.VolumeLevel = 10;
  }
}

public class Radio {
  public int VolumeLevel { 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