HomeSearch

C# value Keyword: Set Property Value

This C# example program shows the value keyword. Value has a special meaning in properties.

Value.

This is a keyword. It is used in properties. In properties in C#, we enjoy a clear and easy-to-read syntax form—and "value" is a part of this.

With parameters in a property,

we can use the special keyword "value." This way we do not need to specify the type. The type is determined by the enclosing property type.

Example.

In this program, each property has a set accessor that uses the value parameter. In the first property, the value parameter is written to the console.
C# program that uses value keyword using System; class Program { int PropertyInt { get { return 1; } set { Console.WriteLine(value); } } string _backing; string PropertyString { get { return this._backing; } set { if (value == null) { throw new ArgumentNullException("value"); } this._backing = value; } } static void Main() { Program program = new Program(); // Use PropertyInt. program.PropertyInt = 5; Console.WriteLine(program.PropertyInt); // Use PropertyString. program.PropertyString = "test"; Console.WriteLine(program.PropertyString); } } Output 5 1 test

Note, assignment.

You can assign the "value" parameter to a new value. So if you want to change a "value" of null to an empty string literal in the second property above, this is possible.NullEmpty String

Discussion.

The C# specification refers to "value" in its description of Accessors in Properties. On page 481, it states "The implicit parameter of a set accessor" is always value.

Also: It might help with understanding how the C# language works to investigate how "value" is implemented here.

Properties: These are actually compiled into methods such as Set_PropertyInt and Get_PropertyInt.

IL

Then: The set method has a regular formal parameter list. The formal parameter has the identifier "value".

Summary.

We examined the value parameter in properties and referenced the language specification. We then discovered the underlying implementation of the value parameter in properties.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.