Problem with objects and automatic numbering in VB.NET

  • Thread starter Thread starter johndevlon
  • Start date Start date
J

johndevlon

Hi everyone,

I'm having a small problem using objects in VB.NET.

I've created a class "Shop" and one of its properties is a number which
I've named "intNumber" (Integer).

I've created several objects of the class Shop and everythink works
fine. What I'm trying to do is to modify my class in such a manner that
when a create a new object, the property "intNumber" has already a
value. Using a constructor you can do this but I would like to give
each object a different number, starting at 1 or 0, increasing 1 each
time a new object has been created...

The first object has automatically number 1 assigned to "intNumber" ,
the second number 2, etc...

I know this is possible but have forgotten how to do this ...

Many thanks

John
 
I'm having a small problem using objects in VB.NET.

I've created a class "Shop" and one of its properties is a number which
I've named "intNumber" (Integer).

I've created several objects of the class Shop and everythink works
fine. What I'm trying to do is to modify my class in such a manner that
when a create a new object, the property "intNumber" has already a
value. Using a constructor you can do this but I would like to give
each object a different number, starting at 1 or 0, increasing 1 each
time a new object has been created...

The first object has automatically number 1 assigned to "intNumber" ,
the second number 2, etc...

I know this is possible but have forgotten how to do this ...

Use a Shared variable to keep track of how many instances have been
created before. Don't forget threading - either acquire a lock while
you're incrementing, or use the Interlocked class.
 
Hi,
Many thanx for the fast responses.

Jon, could you please give a small example ?

John
 
Jon, could you please give a small example ?

Something like this:

Imports System
Imports System.Threading

Class Test

Shared instancesCreated As Integer

Dim id As Integer


Sub New
id = Interlocked.Increment (instancesCreated)
End Sub


Shared Sub Main()

Dim x0 As New Test
Dim x1 As New Test
Dim x2 As New Test
Dim x3 As New Test

Console.WriteLine (x0.id)
Console.WriteLine (x1.id)
Console.WriteLine (x2.id)
Console.WriteLine (x3.id)

End Sub


End Class
 
Hi John,

You must define it as a static member and try working around this.

Regards

Udai.M
Team Leader,Consultant
Chimeratechnologies
Bangalore
 
Back
Top