What is the best way to make declarations and initialize them?

UncleRonin

Well-known member
Joined
Feb 28, 2006
Messages
230
Location
South Africa
Programming Experience
5-10
I'm busy designing a class and a strange thought occurred to me. When you create a class, is it better to declare and set variables directly in the class space or to set them in the New() method? I don't know all that much about the compiler or the way everything is finally put together so I'm absolutely clueless. Maybe one method is faster or one is more suited to a particular situation? Or maybe it all depends on the data type itself?

So which should be used and why (if there is a difinitive reason)
VB.NET:
Public Class Test
   Private Int as Integer = 100
   Private Str as String = "Test"
   Private Obj as Object = SomeObjectThingy
End Class
OR
VB.NET:
Public Class Test
   Private Int as Integer
   Private Str as String
   Private Obj as Object

   Public Sub New()
      Int = 100
      Str = "Test"
      Object = SomeObjectThingy
   End Sub
End Class
 
The class level variables are initialized when the class is created, 'before' constructor method is called, so if ObjectThingy hasn't been created yet you have to assign it at a later stage. A typical example (and beginner mistake) is form initialization where you may have set up a class level variable to reference a UI control, which is not created until after InitializeComponent is done, here you typically assign it for the Load event (or afterwards in constructor). It is cleaner and better OOP to assign the variable value when it is declared if you can.
 
Back
Top