Search code examples
c#.netpass-by-referencepass-by-const-reference

Why does the "in" keyword allow mutation of properties C#?


I am currently working on a function where an object (of self written type Catalog) is passed and shall not be mutated / changed in the called function. Here a quick example.


public override bool Migrate(in Catalog fromCatalog)
{
    fromCatalog.SupplierId = 1; //works, but why
}

I want to strictly undermine this behaviour and disallow mutating any properties of the passed object.


Solution

  • Because the in modifier applies only to the variable (the parameter in this case). It prevents the parameter from having its value changed to refer to a different object.

    public bool Migrate(in Catalog fromCatalog)
    {
    /* Error CS8331  Cannot assign to variable 'fromCatalog' 
    or use it as the right hand side of a ref assignment 
    because it is a readonly variable */
        fromCatalog = new Catalog(); 
    
        fromCatalog.SupplierId = 1;
    }
    

    and create a shallow copy of the object so that you don't change anything in the object you passed (within the class)

    example:

    public Catalog CreateACopy()
    {
        Catalog obj = (Catalog)this.MemberwiseClone();
        // and other...
        return obj;
    }
            
    

    utilization:

    public class Program 
    {
        private static void Main()
        {
            Catalog catalog = new Catalog();
            new Program().Migrate(catalog.CreateACopy());
        }
        public bool Migrate(in Catalog fromCatalog)
        {
            fromCatalog.SupplierId = 1;
        }
    }