Grasshopper

algorithmic modeling for Rhino

what is the difference between Dim ... as New line, and Dim as Line

Hi, is anyone knows why sometimes need new sometime don't need.

example1:

Private Sub RunScript(ByVal x As Object, ByVal y As Object, ByRef A As Object)
Dim m As New Point3d(0, 0, 0)
Dim n As New point3d(0, 0, 1)
Dim h As line
h.From = m
h.To = n
a = h
End Sub

example2:

Private Sub RunScript(ByVal x As Object, ByVal y As Object, ByRef A As Object)
Dim m As New Point3d(0, 0, 0)
Dim n As New point3d(0, 0, 1)
Dim h As New line
h.From = m
h.To = n
a = h
End Sub

They both works,but why?

Views: 1979

Replies to This Discussion

The new command creates a new object on the heap. The result is a ByRef object.

Without new the line is created on the stack. This amounts to a ByVal object.

ByVal is faster to create but the whole object needs to be copied to pass in and out of the Sub. ByRef typically is slower to create, but only a reference to the object needs to be passed in and out of the Sub.

Oh, and since Subs can't return anything, only ByRef objects can be passed out of the Sub.

Are you sure?

I think this is just syntactical indifference of VB.NET and both samples compile to exactly the same MSIL.  I believe in the above example, Rhino.Geometry.Line is a value class (struct) and is always created on the stack.

Copying of value classes is the only type that counts when you are talking about ByVal. Value classes are typically very small in size and copying them has very little overhead.

The "new" keyword is going to be required for creating instances of reference classes since the default would be setting the variable to Nothing without the new.

I very well could be confused though.

-Steve

It's a long time since I actually coded VB. I moved from C++ to C# and never really looked into how it worked internally. Just expectedit to work like it used to... which it obviously doesn't.

Steve is right, new seems to have no more influence on where an instance is created. Structs end up in stack-like memory, classes are placed in heap-like memory.

thanks,a lots.

but, I cannot understand "setting the variable to Nothing". 

here is another example:

dim as new nurbscurve 

if there is new inside the sentence, it causes problem.

You can see the reference for the New keyword in Vb.Net here and in the remarks here. And for C#, here is the explanation of the new operator.

This means that if the is the new functionality involved, then a constructor needs to exist with that signature. Now, all structures have a parameterless constructor that just blanks out memory, so finally you can use "as new ___" in Vb.Net with all structures.

I hope this helps,

- Giulio
________________
giulio@mcneel.com

Thanks Guilio. 

It helps a lot. I think i have to learn more about VB.net.

RSS

About

Translate

Search

Videos

  • Add Videos
  • View All

© 2024   Created by Scott Davidson.   Powered by

Badges  |  Report an Issue  |  Terms of Service