C# String PropertyUse and define a string property with the get and set keywords. Add special logic to the property.
are useful. They give you another level of abstraction on what the string means. We can simplify a program by avoiding null strings (or other values) when those values do not make sense—or will complicate the code.PropertyStrings
First, this example can help you with the basic syntax of using properties, and also string properties. You can declare a property the same way as a field, but you must specify the get and set accessors with those keywords.
Employee: We define an Employee class in the first section. It defines a field and a property, named "_name" and Name.
Name: The Employee property Name in the Employee.cs file accesses the backing store _name field. The field and the property are both of type string.
Note: The set and get keywords in the Name property in Employee.cs both have enclosed blocks.
Also: In the Name get accessor, the "??" operator returns the _name field if it is not null, and string.Empty otherwise.Empty StringNull Coalescing
Class that uses string as property, Employee.cs: C#
public class Employee
public string Name
// Return the actual name if it is not null.
return this._name ?? string.Empty;
// Set the employee name field.
this._name = value;
Main method, Program.cs: C#
static void Main()
// Hire an employee.
Employee employee = new Employee();
// Is the name null?
Console.WriteLine(employee.Name == null);
// Set the name.
employee.Name = "Sam";
// Write the length of employee name.
Notes, Main method.
The Main method creates an instance of the Employee class on the managed heap. It accesses the Name property. Because the _name field in Employee is initialized to null, when you access Name here the value returned is string.Empty.
But: If Name was null, accessing its Length member would result a NullReferenceException.
I have found it useful to define static string properties as global variables in the C# language with custom accessors. The technique of wrapping global variables in accessor methods is described well in Code Complete.
So: This gives you another level of abstraction over your global variables. See Code Complete, 2nd Edition by Steve McConnell, page 340.
other kinds of properties, such as array properties, Microsoft recommends avoiding returning null and instead returning an empty array. This is similar to the null property shown.Array Property
We used strings as properties in the C# programming language. This can help simplify your code and reduce the chance of null references. We inserted logic into the get accessor on a string property.
Also: We saw global variables—and how you can use properties in the recommended way.Global Variable
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.