You can return an IEnumerable
but under the hood it'll be a List
. A developer may well cast it to a List
and add or remove items
I think you're looking for Immutable Collections
Briefly, it's a nuget package that enable us to use/create truly immutable collections; meaning that any collections changes are not reflected back to what exposed them.
EDIT: Cast to IEnumerable does not grant immutability
Given Guilherme Oliveira answer one can do the following and add a new user to the users
var userDictionary = new Dictionary<int, List<User>>();
userDictionary.Add(1, new List<User>
{
new User{ Name= "Joseph"},
});
IDictionary<int, IEnumerable<User>> newDictionary = userDictionary.ToDictionary(p => p.Key, p => p.Value.AsEnumerable());
((List<User>) newDictionary.Values.First()).Add(new User {Name = "Maria"});
Console.WriteLine(newDictionary.Values.First().Count()); //now we have two users