C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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 CoalescingClass that uses string as property, Employee.cs: C#
public class Employee
{
string _name;
public string Name
{
get
{
// Return the actual name if it is not null.
return this._name ?? string.Empty;
}
set
{
// Set the employee name field.
this._name = value;
}
}
}
Main method, Program.cs: C#
using System;
class Program
{
static void Main()
{
// Hire an employee.
Employee employee = new Employee();
// Is the name null?
Console.WriteLine(employee.Name == null);
Console.WriteLine(employee.Name.Length);
// Set the name.
employee.Name = "Sam";
// Write the length of employee name.
Console.WriteLine(employee.Name.Length);
}
}
Output
False
0
3
But: If Name was null, accessing its Length member would result a NullReferenceException.
So: This gives you another level of abstraction over your global variables. See Code Complete, 2nd Edition by Steve McConnell, page 340.
Also: We saw global variables—and how you can use properties in the recommended way.
Global Variable