Suppose a request is made for data from a database that should not be changed, this is a case for ImmutableList . So it depends on your business rules which path to take.
The following prevents add/remove but with auto-properties we can still change properties
public static IReadOnlyList<Categories> GetCategoriesList()
{
using var context = new NorthwindContext();
return context.Categories.ToList().ToImmutableList();
}
public static readonly IReadOnlyList<Categories> CategoriesList = GetCategoriesList();
To prevent add/remove and property changes
public class FromDatabaseMock
{
public static IReadOnlyList<Person> People()
{
return new List<Person>()
{
new ("Karen", "Payne", new List<string>()),
new("Mary", "Jones", new List<string>())
};
}
}
public class Person
{
public Person(string firstName, string lastName, List<string> items)
{
FirstName = firstName;
LastName = lastName;
Items = items;
}
public string LastName { get; }
public string FirstName { get; }
public List<string> Items { get; }
}
Another example, get possible time zones for a DateTimeOffset, we don't want the user to alter the collection.
In a static class
/// <summary>
/// Get possible time zones for a DateTimeOffset
/// </summary>
/// <param name="offsetTime"></param>
/// <returns>time zone names</returns>
public static ImmutableList<string> PossibleTimeZones(this DateTimeOffset offsetTime)
{
List<string> list = new();
TimeSpan offset = offsetTime.Offset;
ReadOnlyCollection<TimeZoneInfo> timeZones = TimeZoneInfo.GetSystemTimeZones();
list.AddRange(from TimeZoneInfo timeZone in timeZones
where timeZone.GetUtcOffset(offsetTime.DateTime).Equals(offset)
select timeZone.DaylightName);
return list.ToImmutableList();
}
current is a nullable DateTimeOffset