Earlier this week, C# 7.2 was released with the new feature of "in" parameter modifier see release notes here
The details provided in the release notes are:"The in modifier on parameters, to specify that an argument is passed by reference but not modified by the called method."
There is not a lot of documentation out on this new feature yet, so I have been trying it out. Seems to work as expected for primitive types, and prevents access to object properties. However, for lists you can still call the methods to modify a List (i.e. Add, Remove, Reverse) and you can actually modify an element directly.
static void Main(string[] args)
{
var test = new List<int>();
test.Add(5);
Console.WriteLine(test[0]);
TestMethod(test);
Console.WriteLine(test[0]);
}
public static void TestMethod(in List<int> myList)
{
myList[0] = 10;
myList.Add(7);
myList.Remove(2);
}
My question is, why can still modify collections when using the "in" parameter modifier?
The
inmodifier only restricts assigning to the reference, but theList<T>is still accessible and mutable. Basically it works likeref readonly.You can't do
myList = new List<int>.