Proper Initialization

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • !NoItAll
    Contributor
    • May 2006
    • 297

    Proper Initialization

    Looking for suggestions on style, correctness in code.

    I have a theoretical function...

    Code:
    Friend Function Foo(byVal fooParam() as String) as Boolean
    Dim Items as Integer = (fooParam.length - 1I)
    Dim sFooStuff(Items) as String
    For I as Integer = 0 to Items
        sFooStuff(I) = fooParam(I)
    Next I
    Return True
    Ok - I know this code does absolutely nothing...
    But - I would like to know how one should initialize the sFooStuff string array.
    As the code is above I get a warning (ok - it is only a warning) that says something bad will be done to my dog because I am using a variable before it has been assigned a value.
    Ok - no big deal (I'm a cat person anyway), but I don't like warnings. I prefer my code to compile with 0 warnings. Warnings mean I have to look at it and analyze it, and ponder it, and really figure out if it is a problem.
    So - to get rid of this annoyance I do this:

    Code:
    Dim sFooStuff(Items) as String = Nothing
    ...which I know is simply a way to tell the Warning engine to shut the &^%$ up. It still leaves the exact same possibility; if I attempt to use the variable before anything is assigned to it, it will throw an exception. But VS now thinks I've set a value. Ha - I'm so smart.

    As the code above tries to illustrate - I really don't have anything to initialize the variable with - as that comes later in the routine.

    So - my question (I know you all were wondering if I would ever get here) - is how do you guys and gals initialize variables that have no New constructor (like String)? Do you live with the warnings? Is my dog doomed?

    Des
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    In C# I would give it an actual set of values -
    If I were using real values it would look like this
    Code:
    string[] sFooStuff = { "dog", "cat", "Mouse", "Eagle" };
    but for your case, I would initialize it to an empty set of values:
    Code:
    string[] sFooStuff = { } ;
    Here the string array is initialized to a set of strings... but without any string. It's subtley but vitally different than setting it to null. Now the array is actually an initialized array, but with a count of zero items.

    Comment

    • !NoItAll
      Contributor
      • May 2006
      • 297

      #3
      My dog thanks you...

      This definately seems more appropriate!

      Comment

      Working...