Results 1 to 3 of 3

Thread: variable problem

  1. #1
    mshahid is offline VB.NET Forum Newbie
    .NET Framework
    .NET 4.0
    Join Date
    Aug 2012
    Posts
    29
    Reputation
    12

    variable problem

    i am new in vb i am trying to demonstrates a function that returns a customer data type. but i got the errors

    "Warning 1 Variable 'Company' is used before it has been assigned a value. A null reference exception could result at runtime",
    Warning 2 Variable 'Address' is used before it has been assigned a value. A null reference exception could result at runtime,
    "Warning 3 Variable 'city' is used before it has been assigned a value. A null reference exception could result at runtime.
    " Warning 4 Variable 'Country' is used before it has been assigned a value. A null reference exception could result at runtime".

    i have tried to solve these but not fix these errors. please tell me how to fix these

    Thanks in advance

  2. #2
    JohnH's Avatar
    JohnH is offline VB.NET Forum Moderator
    .NET Framework
    .NET 4.0
    Join Date
    Dec 2005
    Location
    Norway
    Posts
    14,205
    Reputation
    2369
    Generally you should declare the variable when you need it and assign it a value directly, for example instead of this:
    Dim b As Button
    b = New Button

    you do this:
    Dim b As Button = New Button
    or better yet the short form:
    Dim b As New Button

    If this is not possible you can explicitly assign a null reference to get rid of the warning:
    Dim b As Button = Nothing
    If condition Then
    b = new Button
    Else ...

    By doing this you're telling compiler you're aware that this variable is initially a null reference, and implicitly that you should be taking precautions to avoid causing a null reference exception at runtime later in code.

  3. #3
    Solitaire is offline VB.NET Forum Miyagee
    .NET Framework
    .NET 4.0
    Join Date
    Jun 2004
    Location
    New York
    Posts
    418
    Reputation
    162
    Try assigning a blank string to each of the variables right at the beginning. Example:
    Dim company As String = ""

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Harvest time tracking