Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Optional property in a C# class
An optional property in a C# class is a property that can have a null value without causing runtime errors. Properties whose CLR types cannot hold null values (like value types) cannot be configured as optional unless they are made nullable using the ? operator.
Optional properties are commonly implemented using nullable reference types, default values, or custom attributes to indicate that the property is not required to have a value.
Syntax
Following is the syntax for declaring nullable properties −
public string? PropertyName { get; set; } // Nullable reference type
public int? PropertyName { get; set; } // Nullable value type
Following is the syntax for using a custom Optional attribute −
[Optional]
public string PropertyName { get; set; }
Using Nullable Reference Types
C# 8.0 introduced nullable reference types, allowing you to explicitly mark reference type properties as nullable −
using System;
#nullable enable
public class Employee {
public string Name { get; set; } = string.Empty; // Required
public string? Email { get; set; } // Optional
public int? Age { get; set; } // Optional
public string? Department { get; set; } // Optional
}
public class Program {
public static void Main() {
Employee emp1 = new Employee {
Name = "John Doe",
Email = "john@example.com"
// Age and Department are optional - can be null
};
Employee emp2 = new Employee {
Name = "Jane Smith"
// All other properties are optional
};
Console.WriteLine($"Employee 1: {emp1.Name}, Email: {emp1.Email ?? "Not provided"}");
Console.WriteLine($"Employee 2: {emp2.Name}, Email: {emp2.Email ?? "Not provided"}");
}
}
The output of the above code is −
Employee 1: John Doe, Email: john@example.com Employee 2: Jane Smith, Email: Not provided
Using Custom Optional Attribute
You can create a custom attribute to mark properties as optional for documentation or validation purposes −
using System;
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
internal sealed class OptionalAttribute : Attribute { }
public class Employee {
public string EmpName { get; set; } = string.Empty;
[Optional]
public string? AlternativeName { get; set; }
[Optional]
public string? PhoneNumber { get; set; }
public void DisplayInfo() {
Console.WriteLine($"Name: {EmpName}");
if (!string.IsNullOrEmpty(AlternativeName))
Console.WriteLine($"Alternative Name: {AlternativeName}");
if (!string.IsNullOrEmpty(PhoneNumber))
Console.WriteLine($"Phone: {PhoneNumber}");
}
}
public class Program {
public static void Main() {
Employee emp = new Employee {
EmpName = "Alice Johnson",
AlternativeName = "AJ"
// PhoneNumber is optional and not set
};
emp.DisplayInfo();
}
}
The output of the above code is −
Name: Alice Johnson Alternative Name: AJ
Using Default Values
Another approach is to provide default values for optional properties −
using System;
public class Product {
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public string Description { get; set; } = "No description available"; // Default value
public bool IsAvailable { get; set; } = true; // Default value
public int? Stock { get; set; } // Optional nullable
}
public class Program {
public static void Main() {
Product product1 = new Product {
Name = "Laptop",
Price = 999.99m,
Stock = 10
};
Product product2 = new Product {
Name = "Mouse",
Price = 25.50m,
Description = "Wireless optical mouse"
};
Console.WriteLine($"Product 1: {product1.Name}, ${product1.Price}, Stock: {product1.Stock?.ToString() ?? "Unknown"}");
Console.WriteLine($"Product 2: {product2.Name}, ${product2.Price}, {product2.Description}");
}
}
The output of the above code is −
Product 1: Laptop, $999.99, Stock: 10 Product 2: Mouse, $25.5, Wireless optical mouse
Comparison of Approaches
| Approach | Best For | Benefits |
|---|---|---|
Nullable Reference Types (string?) |
Modern C# applications | Compile-time null safety warnings |
| Custom Attributes | Documentation and validation | Clear intent, can be used by reflection |
| Default Values | Properties that have sensible defaults | Always have a valid value |
Conclusion
Optional properties in C# can be implemented using nullable types, custom attributes, or default values. The choice depends on your specific needs ? nullable reference types provide compile-time safety, while default values ensure properties always have meaningful values.
