I have a class library, and I'm debugging it with a console app. This works perfectly.
The class is intended to be used with an existing Windows service on a server. I don't have a great deal of access to the server.
I update the service to utilize the class library. It's included in the class library in the solution, it's referenced, and it's included on the page.
However, when it's built on the server, it returns a null object.
The relevant service piece:
using MyNamespace;
...
private void TimerTick(){
//this is called every minute
EventLog.WriteEntry("myLog", "Start test", EventLogEntryType.Information);
try
{
EventLog.WriteEntry("myLog", "I see this", EventLogEntryType.Information);
MyClass test1 = new MyClass(); //Error occurs here
EventLog.WriteEntry("myLog", "I never see this", EventLogEntryType.Information);
test1.MyFunction();
}
catch (Exception e)
{
EventLog.WriteEntry("myLog", e.Message, EventLogEntryType.Information);
}
EventLog.WriteEntry("myLog", "Conclude test", EventLogEntryType.Information);
}
And the relevant class:
namespace MyNamespace
{
public class MyClass
{
public SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
public void MyFunction(){
EventLog.WriteEntry("MyLog", "Get links", EventLogEntryType.Information);
}
}
}
In the event log I get the standard:
Object reference not set to an instance of an object.
There are no errors in the build and deploy on the server. The service runs as expected, it's just that null reference exception when trying to instantiate the class.
I'm fairly new to C#/.net
Is there a better way to go about troubleshooting this when the only error messaging I get is through the EventLog?
What are the possible causes of the class instantiation throwing a null reference exception?
Things I tried
First, used Exception.ToString()
to get the stack trace, rather than Exception.Message
like I initially did. This gave me great deal more information to debug with.
Second, looking at the class constructor itself for an error as a class instantiation cannot throw a null reference itself.
The Exception.Message
returns limited information. Better debug information can be logged by using Exception.ToString()
when logging an error:
try
{
//your code
}
catch (Exception e)
{
EventLog.WriteEntry("myLog", e.ToString(), EventLogEntryType.Information);
}
It's also not possible for a class instantiation to to throw a null reference exception - if you see one during an instantiation, something inside the class must be throwing an error. Using Exception.ToString()
should provide the necessary information to identify the specific issue.