How to: Set a Property on an Object

This example sets the CurrentDirectory property on the Environment class to C:\Public.

Example

Environment.CurrentDirectory = "C:\\Public";

-or-

Environment.CurrentDirectory = @"C:\Public";

Compiling the Code

Copy the code, and paste it into the Main method of a console application.

Robust Programming

Use the fully qualified name of the property, unless it is accessible from the same scope.

Unless the property is static, it must be referenced through an instance of the class.

When assigning an expression to a property, make sure of the following:

  • That it is of a compatible data type.

  • That it has a valid value, especially if the value is derived from user input.

If you want more control over possible exceptions, enclose the property assignment in a try-catch statement.

See Also

Concepts

C# Language Primer

Other Resources

Visual C# Express