Why would one ever use the “in” parameter modifier in C#?

后端 未结 5 1969
走了就别回头了
走了就别回头了 2020-12-02 11:08

So, I (think I) understand what the in parameter modifier does. But what it does appears to be quite redundant.

Usually, I\'d think tha

5条回答
  •  悲&欢浪女
    2020-12-02 11:43

    in was recently introduced to the C# language.

    in is actually a ref readonly. Generally speaking, there is only one use case where in can be helpful: high performance apps dealing with lots of large readonly structs.

    Assuming you have:

    readonly struct VeryLarge
    {
        public readonly long Value1;   
        public readonly long Value2;
    
        public long Compute() { }
        // etc
    }
    

    and

    void Process(in VeryLarge value) { }
    

    In that case, the VeryLarge struct will be passed by-reference without creating of defensive copies when using this struct in the Process method (e.g. when calling value.Compute()), and the struct immutability is ensured by the compiler.

    Note that passing a not-readonly struct with an in modifier will cause the compiler to create a defensive copy when calling struct's methods and accessing properties in the Process method above, which will negatively affect performance!

    There is a really good MSDN blog entry which I recommend to carefully read.

    If you would like to get some more historical background of in-introducing, you could read this discussion in the C# language's GitHub repository.

    In general, most developers agree that introducing of in could be seen as a mistake. It's a rather exotic language feature and can only be useful in high-perf edge cases.

提交回复
热议问题