Reputation: 1037
I'm develop an application using ASP.NET in c#, and I hit the following error:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
and this is my code fragment:
Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);
It was testing in my local the code was perfectly fine, but it hit this error when moved the same code to my virtual environment.
I'm guessing maybe it is due to the dot net framework in my virtual environment.
Please help and thank you in advanced.
Upvotes: 2
Views: 3490
Reputation: 1891
replace the code by this :
if(parts != null && parts.Length>0)
{
if(parts[0] != null)
{
Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);
}
}
and it would work fine. The array parts
appears to be null
in your case. But ideally you should also check if the array has elements and if the element in question is not null before you try to convert it to a string value.
Upvotes: 1
Reputation: 19280
Most likely parts[0]
is null. This error is equivalent to a NullPointerException in Java.
Try setting a local variable to parts[0].ToString();
on the previous line, and see if the exception is thrown from that line instead.
I recommend only performing your match if you have something to perform it on:
if(parts[0] != null){
Match matchNew = Regex.Match(parts[0].ToString(), @"([0]\.\d*)|[1]\.[0]$", RegexOptions.IgnoreCase);
}
Upvotes: 4
Reputation: 1185
It seems that your array "parts"
has no elements and therefore parts[0]
is null and the exception occurs due to .ToString()
because null can not be converted to string.
Upvotes: 0
Reputation: 961
From the exception you're getting, it looks like either parts
or parts[0]
is null.
Perhaps consider introducing a variable for parts to see if that is null, and if so, handle either with a default value or display an error to the user, or throw an exception if that is appropriate in your situation.
object part = parts[0];
if (part == null)
{
// part is null, either handle with default value or error.
}
Match matchNew = ...;
Upvotes: 3
Reputation: 1436
Most likely it is your array "parts" if its length is 0 then it will fail. Make sure to test it's length first.
Upvotes: 2