I’m creating a WCF service (.NET 4.0/c#)… I added a new class to the project and I’m trying to instantiate it like so:
MyNewClass inst = new MyNewClass();
… but I’m getting the famous, “Object reference not set an instance of an object” message at that line.
What could I be doing wrong?
EDIT:
Here’s the class:
using System;
using bla, bla, blah...
public class MyNewClass
{
private string cnn1 = ConfigurationManager.ConnectionStrings["connection_string_1"].ConnectionString;
private string cnn2 = ConfigurationManager.ConnectionStrings["connection_string_2"].ConnectionString;
public string Conn(string s)
{
string cnn = string.Empty;
switch (s)
{
case "Server1":
cnn = cnn1;
break;
case "Server2":
cnn = cnn2;
break;
}
return cnn;
}
}
You should pass in a configuration object rather than calling the ConfigurationManager. That would allow you to use the class indenpendent of an appconfig / webconfig.
For instance, perhaps
Or at least check for null before accessing a property,
For instance, change this to be in the contructor