shubham srivastava
shubham srivastava

Reputation: 319

Warning : Variable is passed by reference before it has been assigned a value. A null reference exception could result at runtime

I m working on vb.net and I get the above warning for unassigned reference variable. When I assign Nothing to the variable the warning disappears. Now my question is what difference does assigning a Nothing value makes to a reference variable ?? Even if I don't assign Nothing explicitly then also the default value is Nothing only i guess ?? correct me if i m wrong.

PS : This is what microsoft says "If a variable has never been assigned a value, it holds the default value for its data type. For a reference data type, that default value is Nothing." Here is the complete Link : https://learn.microsoft.com/en-us/dotnet/visual-basic/misc/bc42030

Upvotes: 2

Views: 1938

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54427

You'll notice that it is a warning and not an error. There's nothing specifically wrong with the code, which is why it's not an error. ByRef parameters are used to pass data into and out of methods though, so if you forgot to assign as a value before passing that variable as an argument, an NullReferenceException might be thrown in the method if it assumes that the parameter has a value. By setting the variable to Nothing explicitly, you're telling the compiler that you specifically want the variable to be Nothing and it's not just that you forgot to assign some other value.

Upvotes: 2

Related Questions