I’m using Visual Basic .NET to work with a USB HID device.
Most of the time, I can receive data from it perfectly… but one out of every thousand transfers or so, my code will think it has received data when it actually hasn’t.
The device writes to an array of bytes. I wanted to check to see if the received packet is empty, by doing something like this:
If myDevice.dataPacket(1) <> Nothing then
myDevice.rxDataReady = False
Unfortunately, even with this I get a NullReferenceException, saying that the object reference is not set to an instance of an object.
Is there a different way to do this, or should I just handle a NullReferenceException? If I execute this routine hundreds of times a minute, will adding the exception slow things down at all?
So, a couple of things.
A
Byteis a value type and therefore can never benull. In VB.Net, when you set or check forNothingusing the equality sign=you are actually setting or checking if the value holds “the default value”. For numeric types the “default value” is zero so these two statements are the same:If MyByte = Nothing Then ...If MyByte = 0 Then ....Because of the above rule you should never receive a
NullReferenceException(NRE) when accessing a byte because a byte cannot be null. However, the thing holding a byte can be null. So in your case you should be checking:If myDevice.dataPacket IsNot Nothing ThenDepending on how the bytes within
dataPacketare set you might also want to check thedataPacket.Lengthproperty (after checking thatdataPacketisn’t null) to make sure that there are enough indices in the array. If you go outside of the indices you’ll get aIndexOutOfRangeException.If (myDevice.dataPacket IsNot Nothing) AndAlso (myDevice.dataPacket.Length >= 100) Then