简体   繁体   中英

What is an example of “this” assignment in C#?

Does anybody have useful example of this assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself.

The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you can for a struct type:

public struct MyValueType
{
    public int Id;
    public void Swap(ref MyValueType other)
    {
        MyValueType temp = this;
        this = other;
        other = temp;
    }
}

At any point a struct can alter itself by assigning to 'this' like so.

using the this keyword ensures that only variables and methods scoped in the current type are accessed. This can be used when you have a naming conflict between a field/property and a local variable or method parameter.

Typically used in constructors:

private readonly IProvider provider;
public MyClass(IProvider provider)
{
  this.provider = provider;
}

In this example we assign the parameter provider to the private field provider.

I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.

I've used this to maintain immutability of members while still supporting serialization. Consider a struct defined like this:

public struct SampleStruct : IXmlSerializable
{
    private readonly int _data;

    public int Data { get { return _data; } }

    public SampleStruct(int data)
    {
         _data = data;
    }

    #region IXmlSerializableMembers

    public XmlSchema GetSchema() { return null; }

    public void ReadXml(XmlReader reader)
    {
        this = new SampleStruct(int.Parse(reader.ReadString()));
    }

    public void WriteXml(XmlWriter writer
    {
        writer.WriteString(data.ToString());
    }

    #endregion
}

Since we're allowed to overwrite this , we can maintain the immutability of _data held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee! }

only correct place for this from syntax point of view, is Extension methods in C# 3.0 when you specify first parameter of method as foo(ftype this, ...). and then can use this extension for any instance of ftype. But is's just syntax and not real this ovveride operation.

if you're asked to assign something to this , there's quite a few examples. One that comes to mind is telling a control who his daddy is:

class frmMain
{
    void InitializeComponents()
    {
        btnOK = new Button();
        btnOK.Parent = this;
    }
}

You cannot overwrite "this". It points to the current object instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM