NullReferenceException when accessing some object - c#

I know this is a noob error but I really can't discover why it's coming up as I am accessing an object that is set.
The xloc and yloc both being local variables.
gameBorder.FormInstance.tableLayoutPanel1.GetControlFromPosition(xloc, yloc).BackgroundImage = Properties.Resources.Image;
However this has been set within the form class:
namespace csharp_build
{
public partial class gameBorder : Form
{
public static gameBorder FormInstance;
public gameBorder()
{
FormInstance = this;
InitializeComponent();
}
}
}
Any idea why this happens? Would it be to do with the fact that the form class is referenced as gameBorder, and that is what the constructor is called, and the name for the form class in the solution explorer is Form1.cs?
I know this is a noob problem and I do apolagize but any help would be greatly appreciated.

If you are sure that tableLayoutPanel1 exists and is not null, then change your code to this and see what happens:
var control = gameBorder.FormInstance.tableLayoutPanel1.GetControlFromPosition
(xloc, yloc);
if (control == null) throw new NullReferenceException(
"No control at those coordinates");
control.BackgroundImage = Properties.Resources.Image;
jeez, guys, this is code for analysis, debugging, to help figure out illustrate the cause of the issue, that's all.....
WARNING WARNING WARNING: NOT INTENDED AS FINAL PRODUCTION CODE
Thanks to #SriramSakthivel comments below, please Note that NullReferenceException is being thrown here only for debugging/Analysis purposes, and should never be thrown by application code in production release.

The way you chain members and method results makes it hard to determine at a glance what causes the NullReferenceException to be thrown. FormInstance could be null if it's accessed before any gameBorder instances ever get created. Although unlikely, tableLayoutPanel could be null as well. The result of GetControlFromPosition method could very well be too, if no control is on the specified cell.
When you are encountering this kind of problem within this kind of code, the best thing to do is to decompose the calling chain. This way you will be able to quickly tell where the problem lies.
You can also make code assertions, like this:
var formInstance = gameBorder.FormInstance;
Debug.Assert(formInstance != null);
var controlAtPos = formInstance.tableLayoutPanel1.GetControlFromPosition(xloc, yloc);
Debug.Assert(controlAtPos != null);
controlAtPos.BackgroundImage = Properties.Resources.Image; // You may want to make some assertions on resolving your image instance too
The beauty of code assertions is that it's easy to exclude these from compiling into production code. By default, it's compiled in debug configuration and excluded in release configuration. This way you can benefit from the help it provides on debugging without worrying about the extra overhead in deployed code.
Keep this in mind, it will be useful if you ever face this issue again in the future.

Related

If condition after assertion recommended

Sounds pretty basic, but I did not find an existing answer. Sorry if it's a duplicate.
I have never used assertions much in the past and I may not have understood the spirit behind them yet. Is it recommended or standard practice to write something like the following in method Remove()?
public class Model
{
public Model ParentModel {get; private set}
readonly List<Model> submodels = new List<Model>();
public Model AddSubmodel(Model m)
{
submodels.Add(m);
m.ParentModel = this;
}
public void RemoveSubmodel(Model m)
{
submodel.Remove(m);
m.ParentModel = null;
}
public void Remove()
{
Debug.Assert(ParentModel != null);
if (ParentModel != null) ParentModel.RemoveSubmodel(this);
}
// ...
}
The condition is something I am in control of (i.e. it doesn't depend on user interaction or something) and it determines the correctness of my code, so exceptions are out.
My rationale behind this is, I want it to fail in Debug mode, but I want to repair it as much as possible in Release mode.
Edit: as already mentioned in the comments,
The condition violation is not terribly fatal as such. If there is no parent, other than the the method call failing without the null check, nothing much will happen (in release build).
But what is more important, it indicates that the client of the class Model is doing something that is illogical. I want to be pointed to the fact (at least during debug) that there is something in my client code that I obviously haven't thought about, because if i had, the condition would have never happened.
Assertions are used when some really erroneous condition is true. It is so wrong that an exception is not enough. It is usually use to detect logic errors in your code.
Whether or not to use it in your specific example depends. Are you 100% sure that ParentModel should be non-null, and that if it is null, it implies that something really unexpected and wrong has happened and you must stop the program? If yes, then you can use Debug.Assert. Otherwise, do a null-check and if it is null, handle it by some other way than terminating the program.
Also note that the assert won't work in Release mode. To assert in Release mode, use Trace.Assert.
Learn more here and here.

NullReference at seemingly innocent WeakReference access?

So, I have a piece of code using WeakReferences. I know of the common .IsAlive race condition, so I didn't use that. I basically have something like this:
WeakReference lastString=new WeakReference(null);
public override string ToString()
{
if(lastString!=null)
{
var s=lastString.Target as string; //error here
if(s!=null)
{
return s;
}
}
var str=base.ToString();
lastString=new WeakReference(str);
return str;
}
Somehow, I'm getting a null reference exception at the marked line. By debugging it, I can confirm that lastString is indeed null, despite being wrapped in a null check and lastString never actually being set to null.
This only happens in a complex flow as well, which makes me think garbage collection is somehow taking my actual WeakReference object, and not just it's target.
Can someone enlighten me as to how this is happening and what the best course of action is?
EDIT:
I can't determine at all the cause of this. I ended up wrapping the error code in a try-catch just fix it for now. I'm very interested in the root cause of this though. I've been trying to reproduce this in a simple test case, but it's proven very difficult to do. Also, this only appears to happen when running under a unit test runner. If I take the code and trim it down to the minimum, it will continue to crash when running using TestDriven and Gallio, but will not fail when put into a console application
This ended up being a very hard to spot logic bug that was in plain sight.
The offending if statement really was more like this:
if(lastString!=null && limiter==null || limiter=lastLimiter)
The true grouping of this is more like this:
if((lastString!=null && limiter==null) || limiter=lastLimiter)
And as Murphy's law would dictate, somehow, in this one unrelated test case, lastLimiterand lastString got set to null by a method used no where but this one single test case.
So yea, no bug in the CLR, just my own logic bug that was very hard to spot

MonoTouch mysteriously not aot-compiling methods and properties?

I have a strange problem where MonoTouch seems to be either not compiling methods or not able to find a compiled method it is instructed to call, and only on the device in the Release configuration - Debug builds are fine. I've tried reproducing it with a simpler code sample with no luck, so I doubt you will be able to see the behavior with the code below. But this is essentially what I'm doing:
using System;
using MonoTouch.UIKit;
public class MyClass
{
private UINavigationController _navController;
private UIViewControler _viewController;
public UINavigationController NavController
{
get
{
if (_navController == null)
{
if (_viewController == null)
{
_viewController = new UIViewController();
}
_navController = new UINavigationController(_viewController);
}
return _navController;
}
}
}
Then, in some other method...
public void SomeMethod()
{
MyClass myClass = new MyClass();
var navController = myClass.NavController; // <-- This is where it throws
}
The exception I get is the standard JIT compile message, saying that it attempted to JIT get_NavController(). I find this very strange, because there's no virtual generics, no LINQ, the linker is off, and nothing else that normally causes JITs seems to be involved. I've also verified that it will throw for other methods and properties defined on MyClass, but not the constructor or System.Object inherited methods. Reflection reveals that myClass.GetType().GetMembers() has a MemberInfo for everything I would expect. Yet, only for Release|iPhone, I can't access these methods or properties. The only logical conclusion I can come to is that the aot compilation step is missing them, and I don't know why that would happen at all, let alone only in the Release configuration.
My question is, what could be causing such a situation, and what is the next step to fixing it? I'm not even sure where to go from here on debugging this, or what to file a bug about, because I can't reproduce it out of the context of our (much) larger project.
Update: The exact exception text was requested.
System.ExecutionException: Attempting to JIT compile method
'MyNamespace.MyClass.get_NavController ()' while running with --aot-only
This doesn't look like something that can be solved here.
I suggest filing a bug, and attach the entire project if you're unable to make a smaller test case. You can file private bugs only Xamarin employees have access to if you don't want your project to be publicly visible.
Could you try to explicitly declare the variable
UINavigationController navController = myClass.NavController;
Alternatively, I wonder if this is at all associated with needing to wait for the UIViewController.ViewDidLoad method to be called as the internals of the class may not yet have been initialized?
Just shots in the dark here, I can't think of a reason why your code wouldn't work.

what would make the "this" clause different?

I have the following code:
CustomerService service;
public CustomerService Service
{
get
{
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
}
}
public DataTable GetCustomers()
{
return this.Service.GetCustomers();
}
Now the question is: if I wrote the above method as follow (without "this"), it's giving me an error : instance is not reference to an object.
public DataTable GetCustomers()
{
return Service.GetCustomers(); // this will spell the error "instance is not reference to an object"
}
Does anyone know? also it only happens while running via IIS and not from casini web server (VS 2010).
The presence or absence of this cannot explain the error you are witnessing. In this situation they mean exactly the same thing and will compile to the same IL code. Check the assembly using .NET Reflector to verify this if you wish. The error is occurring at random, probably due to a race condition.
One thing I can immediately see is that if you are running this code from multiple threads then it looks like you have a race condition here:
if (this.service == null)
{
this.service = new CustomerService();
}
return this.service;
In the multithreaded case you would need to lock otherwise you could get two CustomerService objects. I'm not sure if this explains your error, but it certainly could create confusion. Race conditions can occur in one environment but not in another as the frequency of the error can depend on the type of the hardware and on what other processes are running on the server.
You may also have other race conditions in the code you haven't posted. Don't use this lazy initialization technique without locking unless you are sure that you have only one thread.
You probably have a name conflict with another 'Service' (class or namespace). The use of this solves it.
I'm a bit skeptical about the difference between Cassinin and IIS, have you carefully checked that?
Something like this should be in a singleton. Which would resolve many issues like threading if implemented correctly and would make the implementation and readability of the code much better.
Thanks
-Blake Niemyjski (.netTiers team member)
I fiddled a bit with your code in Visual Studio and I couldn’t even get a name conflict to produce the error message you described. I can’t think of any case in which “this.X” can ever be different from “X” except when “X” is a local variable or a method parameter.
Would the CustomerService class derive from a base class called Service? If so, then that's the problem.

Interview Question in C#

A Technical Lead asked me the following:
He created a class, declared an object and initialized it. But in some circumstance we may get "null reference" exception.
He commented that there are 1000 possible reasons for such exception and asked me to guess a single reason.
I am unable to figure it out. What is (are) the reason(s) ,we may get such an exception?
You have used an object reference you have explicitly set to null, or
You have used an object reference you have implicitly set to null, or
Somewhere in your code, or in code called by you, there is the statement throw new NullReferenceException() (which you shouldn't do, by the way). I don't know if this counts, since it's not a real null reference.
I can't think of any of the other 997 reasons.
Edit: Thanks, Mark Byers, for point 3.
If it's a multi-threaded app, then some other thread could come along and set the object to a null reference.
Stack overflow?
{◕ ◡ ◕}
A few ways I can think of:
The constructor can throw a NullReferenceException before it completes.
When you access a property, the property can throw a NullReferenceException.
If you have a try { } finally { } around the code, if it throws an exception the finally runs and the code in the finally could throw a NullReferenceException.
There could be an implicit conversion during the assignment and the code for the conversion throws a NullReferenceException.
Here's example code for the last:
class Foo {}
class Bar
{
public static implicit operator Foo(Bar bar)
{
throw new NullReferenceException();
}
}
class Program
{
public static void Main()
{
Foo foo = new Bar(); // This causes a NullReferenceException to be thrown.
}
}
He created a class, declared an object
and initialized it. But in some
circumstance we may get "null
reference" exception. He commented
that there are 1000 possible reasons
for such exception and asked me to
guess a single reason. I am unable to
figure it out. What is (are) the
reason(s) ,we may get such an
exception?
Straightforward answer: I'd tell the interviewer that you can't debug code you can't see. Ask to see offending line of code and a debugger.
Not-so-straightforward answer: assuming your interviewer isn't an idiot, he probably feeling you out for your debugging skills. If you get a crappy bug report, do you throw your arms up and surrender right away, or do you attempt to resolve it.
Guessing is not an acceptable way to debug the error. The first step would be reproducing the bug on your machine.
Does it reproduce reliably? If yes, get your debugger out.
If no, can you reproduce it intermittently, or non-deterministically? Does the exception occur randomly in different places in code or on different threads? If yes, you probably have some sort of race condition, or maybe a corrupted pointer.
If no, ask whoever found the bug to reproduce. When you follow the same steps as the person who originally found the bug, can you reproduce? If yes, see above.
If no, is there are a difference in environments? Configuration files? Data in the databases? Is the environment updated with the latest service packs, software updates, etc?
You won't be able to give your interviewer an answer, but you can give him a list of steps you'd take to eventually get to an answer.
Not an expert, but just a wild guess, out of memory?
You can always initialize something to a null value;
public class MyClass
{
// initialized to null
private string _myString = null;
// _myString is initialized, but this throws null reference
public int StringLength { get { return _myString.Length(); } }
}
The object in question may contain other objects that are not initialized in the main object's constructor. The question doesn't specify where or when the null reference exception is occurring.
999 to go.
In Multi-threaded code the variable can be accessed after the object has been created, but before the variable has been assigned to its location.
I think the interviewer was actually looking for how you'd go about solving the problem, ie what troubleshooting steps you'd take to solve a problem that could be caused by a thousand different things.

Categories