ekkis
ekkis

Reputation: 10226

How can an object refer to itself?

in Javascript every object carries a this which refers to itself. How can a field in a class be created to refer to the object that contains it?

- addendum -

to clarify, what I mean is that if I declare:

Class xc
  Private i As Integer
End Class

and then make the reference:

Dim x As New xc()
x.Me

I get the error:

'Me' is not a member of 'MyProject.xc'. - \x...\test.vb(3) - Source Line: x.Me

incidentally, the question arises from the following, related question: How to refer to an object created by "with" within the construct?

Upvotes: 1

Views: 4253

Answers (4)

Fabio
Fabio

Reputation: 32445

You don't need to refer to instance of class, because your instance is a reference. So your code x.Me will be just x.

Me(VB.NET) or this(C#) are reference to instance of class only inside of this instance

From MSDN:

A class is a reference type. When an object of the class is created, the variable to which the object is assigned holds only a reference to that memory.

But if your realy want to have a memeber of class, then just create a memeber of type of your class and assign it like this:

Public MyPreference as YourClass

and then assign it

Me.MyReference = Me

Upvotes: 0

ekkis
ekkis

Reputation: 10226

haha. this seems to work.

Public Class XC
    Public Self As XC = Me
End Class

Dim x As New XC()
Dim y As XC = x.Self

Upvotes: 1

KekuSemau
KekuSemau

Reputation: 6853

This is Me in Visual Basic.

Public Class Form1
    Sub test()
        MsgBox(Me.Text)
    End Sub
End Class

http://msdn.microsoft.com/en-us/library/20fy88e0.aspx

Upvotes: 2

Mike Cole
Mike Cole

Reputation: 14743

VB.NET has the Me keyword.

Me.Name = "Name"

Upvotes: 4

Related Questions