I am having a nullreferenceexception error in my code in this line:
public bool BoundingVolumeIsInView(BoundingSphere sphere)
{
**return (Frustum.Contains(sphere) != ContainmentType.Disjoint);**
}
Please tell me what i am doing wrong?
Thanks
Frustum is probably null. Use a debugger and check it. You could do something like this to prevent null pointer exceptions
if(Frustum != null)
return (Frustum.Contains(sphere) != ContainmentType.Disjoint);
return false;
Related
C# seems to allow to compare between primatives (bool, int) to null.
bool a = true;
if (a != null)
{
return null;
}
Console.Write("a");
Furthermore it doesn't generate
Warning:
Unreachable code detected
That you will get when changing a != null to true.
Changing a != null to true != null won't compile.
Is there an explanation for this behavior? Or is it a compiler bug?
I have a very simple check right at the beginning of one of my methods as follows:
public void MyMethod(MyClass thing)
{
if(thing == null)
throw new ArgumentNullException("thing");
//Do other stufff....
}
But I'm getting stacktraces (from Elmah in a production environment) which appears to indicate that the "if(thing == null)" line is throwing a NullReferenceException. The first 2 lines of the stack trace are something like:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at MyLibrary.BL.AnotherClass.MyMethod(MyClass thing) in C:\Development\MyProject\trunk\MyLibrary.BL\AnotherClass.cs:line 100
MyClass is a fairly simple class with no operator overloads or anything like that, so I'm a bit stumped as to what is throwing the NullReferenceException!
Can anybody suggest scenarios that might cause this?
EDIT: I suspect "thing" might be null, but I really would expect an ArgumentNullException not a NullReferenceException - this is basically what this question is about. Is there maybe something that the framework or Elmah that is changing or mis-reporting the exception - or is the only explanation that the binaries are somehow out of date?
It is impossible for if (thing == null) to throw a NullReferenceException.
This means that something else is going on. It's time to start using your imagination in conjunction with a firm resolve to ignore the possibility that the if caused a problem.
The if statement can throw a NullReferenceException if MyClass defines the == operator incorrectly e.g.
class MyClass
{
int A {get;set;}
public static bool operator ==(MyClass a, MyClass b)
{
return a.A == b.A;
}
public static bool operator !=(MyClass a, MyClass b)
{
return !(a == b);
}
}
Looks like the exception is coming from something up the chain that calls MyMethod. MyMethod() is throwing the Exception and nothing above is handling it, so whatever web framework you're in is throwing the HttpUnhandledException.
I also encountered this impossible situation. It turned out to be due to the use of the as keyword, I have no idea why. I was using the SharpPdf library and had a line of code like this:
var destElement = annotDict.Elements["/Dest"] as PdfName;
if (destElement == null)
{
continue;
}
If I remove the as PdfName portion, it works. So I now have two levels of checking in my code:
var destElement = annotDict.Elements["/Dest"];
if (destElement == null)
{
continue;
}
var destElementName = destElement as PdfName;
if (destElementName == null)
{
continue;
}
thing is null.
That would cause it.
[EDIT]: Here's the code I tested with:
protected void Button3_Click(object sender, EventArgs e)
{
MyMethod(null);
}
public void MyMethod(String thing)
{
if (thing == null) // This caused the exception to be thrown.
throw new Exception("test");
//Do other stufff....
}
I'm compiling a program which was originally build in Visual C# 2005. I'am using visual C# 2010. And I keep getting "NullReference Execption was unhandled" errors when running the program on the following functions:
The error occurs on the line with DataBuffer. DataBuffer is an private string set to null on initialisation.
if (DataBuffer.Contains(ok))
{
okFound = true;
}
and
string temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (temp != null)
{
parseDeviceType(temp);
}
checkTypeFound();
}
When I check what the value of DataBuffer is in the code above (when I get the error) this is not null. It actually contains the data I expect.
DataBuffer information is loaded in this function:
private void ser1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (ser1.BytesToRead > 0)
{
string data = ser1.ReadExisting();
DataBuffer += data;
}
}
The serial port is opened somewhere else in the code. There have been no changes to the code only the compiler is different. What line should I add, and where to solve this error? Note, I can prevent this error from happening using an if and try-catch statement. But this is not what I'm looking for, I need this code to work.
This application has not been changed in any way other than the compiler.
You should check if DataBuffer is null before you call its methods.
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
// or simpler:
okFound = (DataBuffer != null && DataBuffer.Contains(ok));
and your second code snipped should check for null as well.
string temp = String.Empty;
if (DataBuffer != null)
temp = getLine(DataBuffer.Substring(mylocation));
if (!checkTypeFound())
{
if (!String.IsNullOrEmpty(temp))
parseDeviceType(temp);
checkTypeFound();
}
Try using the following:
if (DataBuffer != null && DataBuffer.Contains(ok))
{
okFound = true;
}
You should set the value of DataBuffer to something other than null in your constructor. If you can't do that then you may set it to string.Empty instead of null to avoid null exception. But it always better to check for null before initiating an instance method on object.
Code below is placed in page_Load. How I should handle this to bypass UrlReferrer when you enter page directly first time and there is no referrer?
What I am missing here?
if (HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Just check UrlReferrerfor null:
if (HttpContext.Current.Request.UrlReferrer != null
&& HttpContext.Current.Request.UrlReferrer.AbsoluteUri != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Who says the client passed by the referrer in the HTTP request?
Check if UrlReferrer is null first
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
Why not this way much cleaner than checking nulls
private void Page_Load()
{
if (!IsPostBack)
{
if (HttpContext.Current.Request.UrlReferrer != null)
{
urlReferer = HttpContext.Current.Request.UrlReferrer.AbsoluteUri.ToString();
}
else
{
urlReferer = "";
}
}
}
I believe you need to check if HttpContext.Current.Request.UrlReferrer != null.
If UrlReferrer is null, then the test to AbsolutUri will fail.
Try initially testing UrlReferrer for null, this will probably correct the issue.
Use your debugger. If you're running this out of visual studio, than you might be brought to a debugger window when the exception is thrown. There are multiple tabs at the bottom of the debugger including "Locals" and "Watch" you can use those to see what variables are being stored.
If the above code is indeed what's causing the problem than
HttpContext.Current.Request.UrlReferrer.AbsoluteUri
or
HttpContext.Current.Request.UrlReferrer
or
HttpContext.Current.Request
or
HttpContext.Current
or
HttpContext
is set to null
Hai,
In my code while executing a function i got regularly the exception error as "Object reference not set to an instance of an object"
The function exceuting is as follows
private void PageHeaderSetting(Graphics g)
{
try
{
DataTable dtPageHeader=new DataTable() ;
dtPageHeader = ds.Tables["Page Header"];
if (dtPageHeader.Rows.Count != 0)
{
foreach (DataRow dr in dtPageHeader.Rows)
{
if (dr.ItemArray[0].ToString() != "")
PageHeaderText = dr.ItemArray[0].ToString();
else
PageHeaderText = "";
if (dr.ItemArray[1].ToString() != "")
PageHeaderFont = (Font)dr.ItemArray[1];
else
PageHeaderFont = new Font("Tahoma", 18, FontStyle.Bold, GraphicsUnit.Point);
if (dr.ItemArray[2].ToString() != "")
PageHeaderFormat = AlignmentSetting(dr.ItemArray[2].ToString());
else
PageHeaderFormat = AlignmentSetting(Convert.ToString(Alignment.Left));
if (dr.ItemArray[3].ToString() != "")
PageHeaderColor = (System.Drawing.Color)dr.ItemArray[3];
else
PageHeaderColor = Color.Black;
PageFooterText = Word_Wrap(PageHeaderText, PageHeaderFont, g, 0);
PageHeader(g);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
How can i solve this.Can anybody help me?
From the second line i got the exception error
means after declaring the datatable and putting the ds.Tables in it from there erroe occurs
This exception means you're trying to call a method on a null object. The exception should have given you a stack trace with the line number it was thrown at; this'll help you pin it down a bit. You could also try debugging it in visual studio and see where the exception is thrown & see what is null.
Instead of using ToString() to check if you have a value in the ItemArray you should check the actual value. Check for ItemArray[0] == null and ItemArray[0] == DBNull.Value.
Edit:
From your comment it seems that there may not be any data table named "Page Header" in your data set.
Try to add a null check to your DataTable object after the line dtPageHeader = ds.Tables["Page Header"];
Something like this:
if (dtPageHeader == null)
{
// There is no table named Page Header
}
Look at the line number in the exception.
Your code has numerous chained calls, which is a common source of this exception. If either of these chained properties returns null, the "next" call in the chain will fail with a NullReferenceException.
One of this could be true:
ds is null
A Value on a columun in dtPageHeader is null