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

前端 未结 6 2303
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 01:46

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

6条回答
  •  猫巷女王i
    2020-12-11 02:13

    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.

提交回复
热议问题