Saturday, March 24, 2012

The difference between creating an instance of an object

Could someone tell me in plain english was is the difference between


Dim MyObject As SomeType

and


Dim MyObject As New SomeType

and


Dim MyObject = New SomeType
Dim MyObject as SomeType = Creating a variable that holds an object of SomeType.

Dim MyObject as New SomeType = Creating and instantiating an object of SomeType.

Dim MyObject = New SomeType = Invalid syntax in vb.net. You need to specify the default type as variant is no longer supported in ASP.NET.
Ok, now I understand.

So if I have something like Fruit.Apple and Value is part of this as in Fruit.Apple.Value, I can do this...

Dim Food As Fruit.Apple

Food.Value

It looks like a way of shortening the name of an object.

Now, I have another question. How do you know when is the appropriate time to create and instantiate a new object rather than just use the above method?

Sorry if my question seems too easy, but I didn't do much of this stuff in regular ASP.
Well yes and no.

Lets think of this another way. Lets take your Fruit object. Your fruit has properties - color, weight, type, etc. You would create a class that describes this like so:


Public Class Fruit
Private _type As String
Private _color As String
Private _weight As Decimal

Public Property Type() As String
Get
Return _type
End Get
Set(ByVal Value As String)
_type = Value
End Set
End Property
' Add other properties for color and weight also

End Class

Then in your code you would instantiate a new Fruit object like:


Dim objFruit as New Fruit
'Then set properties of the fruit
With objFruit
.Type = "Apple"
.Color = "Red"
.Weight = 2.2
End With

It is appropriate to create a class whenever you are going to possibly reference the object from multiple places in your code.

Greg

0 comments:

Post a Comment