what is 'this' keyword for?

  • Thread starter Thread starter vaughn
  • Start date Start date
V

vaughn

What is the 'this' keyeword for? If I'm filling a textbox, what's the
difference between
this.textbox1.Text = "my text"; and textbox1.Text = "my text"; ?
I normally use it w/o the 'this'.
Thanks.
 
When you are writting code in method or property of a class, using "this"
will allow you to make use of the intellisense.
I guess this is particulary usefull in Winform apps. There are so many
properties/methods to use...

appart from that in the situation you mentioned, there is no diff. at all

José
 
"this" represents the instance of the current object you are on.
Lets say that you have a:
class Test{
TextBox t1 = new TextBox();
public void Method(){
TextBox t1 = new TextBox();
this.t1.Text = "blah"; // calls the textbox that belongs to the
class.
t1.Text = "blah2"; // calls the textbox that belongs to the method.
//both textboxes are completely different, and they have nothing to
do //with each other. One has a broader scope (the one that is
defined //first) while the scope of the second one is limited to
the method //"Method()"
}
}
 
Hi vaughn,
You can used with or without *this*. Using *this* may make the code clearer
and it helps when use InetlliSense.
Hoever *this* is necesarry to solve ambiguities when you have local variable
and type member with the same name.

HTH
B\rgds
100
 
The this keyword signifies the current class scope and is used to clarify
access to members of the current instance of a class..

It is analagous to the VB Me keyword.

When programming nonstatic member methods and properties, the this keyword
gives you access to members in the current class scope.

When in a static method, the this keyword will be unavailable because static
members must not access instance data.

Examples;

class c
{

int a; // defines a member field

this.a=10 //invalid this must have an instance of the class

static void foo()
{
this.a=10; // invalid, this must have a running instance of a class
}

public void boo()
{
a=10; /valid analagous to this.a
this.a=10; //valid refers to the a field "a" in the current instance
}

}

Hope this helps...


--
Bob Powell [MVP]
C#, System.Drawing

September's edition of Well Formed is now available.
http://www.bobpowell.net/currentissue.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm
 
Hi Bob,

I don't see any reason why c# prohibits calling static method or access
static field using an instance (reference (including *this*) or a name of
the value-type variable)

Ultimately any variable has exact type at compile time.
AFAIK Managed C++ allows this.

B\rgds
100
 
Thus spake 100:
Hi Bob,

I don't see any reason why c# prohibits calling static method or
access static field using an instance (reference (including *this*)
or a name of the value-type variable)

A static method does not have an implicit this pointer. Additionally,
static methods are called from the class, not an instance of the class.

Or am I missing something?
 
100 said:
I don't see any reason why c# prohibits calling static method or access
static field using an instance (reference (including *this*) or a name of
the value-type variable)

Because it causes confusion - it makes it appear that it will be called
polymorphically, or have something to do with that particular object,
when in reality it doesn't.

For instance, suppose I could write:

Thread t = new Thread (new ThreadStart(Foo)).Start();
t.Sleep (1000);

What does that second line suggest to you? It would suggest to me that
the author is trying to make the new thread sleep for a second. In
fact, it would make the *current* thread sleep for a second, as
Thread.Sleep is static and *always* applies to the current thread.
Ultimately any variable has exact type at compile time.

I'm not exactly sure what you mean by this, but note that:

Foo x = new Bar();

means that the value of x is a reference to a Bar instance - and
methods called on x may be different to methods called on a Foo
instance - but only when the methods are instance methods. (The
compiler won't actually know that x contains a reference to a Bar.)

In Java you could even do:

Foo x = null;
x.DoSomething();

and it would execute fine - no null pointer exception or anything,
despite the way it *looks* like it's dereferencing x.
AFAIK Managed C++ allows this.

Java allows it to - and it causes confusion. Fortunately Eclipse now
has an optional warning/error to alert you to this.

I was very pleased to see that C# disallows it.
 
Frank Oquendo said:
Thus spake 100:


A static method does not have an implicit this pointer.

You are completely right. that mens that you cannot use any instance methods
from inside the static method

Additionally, static methods are called from the class, not an instance of
the class.
This is only C# (and AFAIK VB.NET) limitation and I don't see any reason for
this.

Consider this:

class A
{
public static void StaticFoo()
{
}

public void InstanceFoo()
{
//At compile time C# compiler perfectly knows the type of this and
can translate the line to A.StaticFoo();
//For C# compiler this is error, though. Why?
this.StaticFoo();
}
}

....
A a = new A();
a.StaticFoo();
Again, the compiler perfectly knows that *a* is of type A and can translates
this line to A.StaticFoo();

even the following can be possible
A a = null;
a.StaticFoo();

Because I know one can argue that the run-time type is not known during
compilaton I want to say that this is not a problem at all. The same is true
for instance methods as well.

B\rgds
100
 
Thus spake 100:
This is only C# (and AFAIK VB.NET) limitation and I don't see any
reason for this.

Actually, Java does this as well and I believe it is by design, not by
requirement. The argument is that forcing static method calls through
the class and not an instance reduces confusion.

I remember having to learn the difference between '.', '->' and '::' in
C++. I must say, I find C# a lot easier to work with since there's only
the dot operator. While I do think it would be sensible to allow access
to static methods via an instance, the consistency is worth the trade.
 
100 said:
//For C# compiler this is error, though. Why?
this.StaticFoo();

Because it's misleading. It leads the reader to assume that the "this"
part is important, when it's not at all.

Why would you *want* to do the above anyway?
 
Jon,
For instance, suppose I could write:

Thread t = new Thread (new ThreadStart(Foo)).Start();
t.Sleep (1000);
Yep, this is exatly what I was after. I was looking for reasonable
explanation for this limitation since I found out that C# prohibit this.
That is a perfect one.
I'm not exactly sure what you mean by this, but note that:

Foo x = new Bar();

means that the value of x is a reference to a Bar instance - and
methods called on x may be different to methods called on a Foo
instance - but only when the methods are instance methods. (The
compiler won't actually know that x contains a reference to a Bar.)

The type of the variable *x* is Foo. you cannot use any member (staic or
instance) that is not among Foo's members. In the example you have access
only to Foo part of Bar's intrerface. Got it?
Type of the *variable* and type of the *object* it references are two
different things.
So speeking static members there is not problem with this .

In Java you could even do:

Foo x = null;
x.DoSomething();

and it would execute fine - no null pointer exception or anything,
despite the way it *looks* like it's dereferencing x.

Yes, I don't see any propblem with this.
Java allows it to - and it causes confusion. Fortunately Eclipse now
has an optional warning/error to alert you to this.

I was very pleased to see that C# disallows it.

I have't had any problems with this in C++, but with the example you gave me
I agree that this is a good decision.

B\rgds
100
 
Frank Oquendo said:
Actually, Java does this as well and I believe it is by design, not by
requirement. The argument is that forcing static method calls through
the class and not an instance reduces confusion.

Actually, Java *doesn't* do that. You often see people writing:

Thread.currentThread().sleep(1000); in Java, unfortunately.
While I do think it would be sensible to allow access
to static methods via an instance, the consistency is worth the trade.

Why would that be sensible though? I still don't see any benefit
whatsoever - and the downside is readability.
 
Thus spake Jon Skeet:
Why would that be sensible though? I still don't see any benefit
whatsoever - and the downside is readability.

An instance should have access to all members contained by its
definition. However, that would imply that instance methods are callable
from the class. I think C# got it right.
 
Yep, this is exatly what I was after. I was looking for reasonable
explanation for this limitation since I found out that C# prohibit this.
That is a perfect one.

Goodo :)
The type of the variable *x* is Foo.
Yes.

you cannot use any member (staic or
instance) that is not among Foo's members. In the example you have access
only to Foo part of Bar's intrerface. Got it?

Although you can't use any member that is not among Foo's members, the
implementation you use may be Bar's implementation, not Foo's. Now when
calling static methods, that wouldn't be available - which would be
confusing.
Type of the *variable* and type of the *object* it references are two
different things.
So speeking static members there is not problem with this .

Only in terms of expectations. I've seen people expect different
behaviour before now, in Java.
Yes, I don't see any propblem with this.

The problem is that it looks like it's dereferencing x, but it's not.
Anything that looks like it's doing something that it isn't is a bad
idea, IMO.
I have't had any problems with this in C++, but with the example you gave me
I agree that this is a good decision.

Goodo.
 
Jon,
Because it's misleading. It leads the reader to assume that the "this"
part is important, when it's not at all.

Why would you *want* to do the above anyway?

I don't want to use it. I just had a suspicion that there has to be some
reson for that. So far I have the impression that C# is really modern
language and the things usualy have reasonable explanation. In your previuos
post you gave me the perfect example.
 
the keyword "this" is most widely used in a class' constructor:

class Dog
{
string name;
int age;

public Dog(string name, int age)
{
this.name = name; // here "this.name" refers to the class' field
"dog", and "name" refers to the parameter
this.age = age; //again, this.age refers to the field "age", "age"
refers to the param
}
}

It is also used when you are trying to pass the instance as a parameter, for
example, suppose that the class Dog implements the interface IDog, which
looks like:

public interface IDog
{
void Bark();
}

and you have the following static function, which will call the Bark
function for any class that supports IDog.

public static Bark(IDog theDog)
{
theDog.Bark();
}

Now, within the scope of the class Dog, you can call the static function
Bark anywhere by passing "this" as a parameter:

TheStaticClass.Bark(this);

of course, this is eventually equalvalent as this.Bark(); since the
parameter "theDog" in the static function will represent the current
instances, and thus function Bark() in the class Dog is invoked.

This is not a good example to demostrate why you would use 'this' as a
parameter. But let's just say that somethings you wanna do it.

Regards,
Peter
 
Back
Top