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.
Thank you!
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.
Thank you!
You cannot overwrite "this". It points to the current object instance.
Not sure if I completely understand your question, but if someone asked you "Why might you assign a value to the 'this' keyword in C#?" then either they are idiots or it was a trick question.
You cannot assign a value to the "this" keyword in C#.
EDIT: Apparently you can assign to the "this" keyword within a struct. I guess I need to use structs more often... ;)
EDIT: If, on the other hand, someone is talking about assigning the value of "this" to another variable, that would be different.
public class Node
{
...
public void AddChild(Node childNode)
{
childNode.ParentNode = this; // this node will be child node's parent
}
...
}
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.
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.
public class Test {
int id;
public Test(int id) {
this.id = id;
}
public Test(Test test) {
this = test;
}
}
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;
}
}
"this" is a reference to the current class instance. If you have a non-static method on a class, you can refer to the current class instance using this:
public class MyClass{
public string SomeProperty {get;set;}
public void GetSomeProperty(){
return this.SomeProperty;
}
}
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.