What advantage is there to storing “this” in a local variable in a struct method?

As you already noticed, System.Collections.Immutable.ImmutableArray<T> is a struct:

public partial struct ImmutableArray<T> : ...
{
    ...

    T IList<T>.this[int index]
    {
        get
        {
            var self = this;
            self.ThrowInvalidOperationIfNotInitialized();
            return self[index];
        }
        set { throw new NotSupportedException(); }
    }

    ...

var self = this; creates a copy of the struct referred to by this. Why should it need to do that? The source comments of this struct give an explanation of why it is necessary:

/// This type should be thread-safe. As a struct, it cannot protect its
own fields
/// from being changed from one thread while its members are executing on other threads
/// because structs can change in place simply by reassigning the field containing
/// this struct. Therefore it is extremely important that
/// ** Every member should only dereference this ONCE. **
/// If a member needs to reference the array field, that counts as a dereference of this.
/// Calling other instance members (properties or methods) also counts as dereferencing this.
/// Any member that needs to use this more than once must instead
/// assign this to a local variable and use that for the rest of the code instead.
/// This effectively copies the one field in the struct to a local variable so that
/// it is insulated from other threads.

In short, if it is possible that other threads are making changes to a field of the struct or changing the struct in place (by reassigning a class member field of this struct type, for example) while the get method is being executed and thus could cause bad side effects, then it becomes necessary for the get method to first make a (local) copy of the struct before processing it.

Update: Please also read supercats answer, which explains in detail which conditions must be fulfilled so that an operation like making a local copy of a struct (i.e. var self = this;) is being thread-safe, and what could happen if those conditions are not met.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)