Results 1 to 4 of 4

Thread: I can't seem to set an object variable to an integer or single whose value is zero

Threaded View

  1. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: I can't seem to set an object variable to an integer or single whose value is zer

    If it's not working then you're doing it wrong. As you haven't actually shown us what you're doing, we can't tell you what's wrong with it. If you run this code you'll see that there's no way that you should be getting a NullReferenceException when puling an Integer or Single from an Object variable, even if you have in fact assigned Nothing to the variable.
    vb.net Code:
    1. Module Module1
    2.  
    3.     Sub Main()
    4.         Dim number As Object
    5.  
    6.         number = Nothing
    7.         Console.WriteLine(CInt(number))
    8.         number = 123
    9.         Console.WriteLine(CInt(number))
    10.         number = 0
    11.         Console.WriteLine(CInt(number))
    12.         number = 456
    13.         Console.WriteLine(CInt(number))
    14.         number = Nothing
    15.         Console.WriteLine(CInt(number))
    16.  
    17.         number = Nothing
    18.         Console.WriteLine(CSng(number))
    19.         number = 12.34F
    20.         Console.WriteLine(CSng(number))
    21.         number = 0.0F
    22.         Console.WriteLine(CSng(number))
    23.         number = 56.78F
    24.         Console.WriteLine(CSng(number))
    25.         number = Nothing
    26.         Console.WriteLine(CSng(number))
    27.  
    28.         Console.ReadLine()
    29.     End Sub
    30.  
    31. End Module
    As I said, Nothing corresponds to zero for numeric types so if you convert a null reference to a numeric type then you get zero.

    If you're always going to be storing an Integer or a Single then why not just declare the variable as type Single? You'll always be able to store an Integer in it. If you want to be able to distinguish a value that should be an Integer rather than a Single then use a Boolean flag. You'd need that when using Object anyway. Also, if you actually use a value type then you could declare it as nullable, which would then allow you to distinguish between zero and no value.
    Last edited by jmcilhinney; Oct 6th, 2016 at 09:44 PM. Reason: Added missing code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Tags for this Thread

Posting Permissions

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



Click Here to Expand Forum to Full Width