0

In my projects, I used connection string inside non-static classes, and It works fine. But now I'm developing a project that uses connection string inside static classes. In the code below the Catch block will throw an error as shown below:

NullReferenceException: Object reference not set to an instance of an object.

If I comment out this line "Throw" it works fine, but I want to understand what went wrong in my code.

DataAccess class:

public class DataAccess
{
    static string connstr =  ConfigurationManager.ConnectionStrings["DbSystem2018"].ConnectionString;

    public static object GetSingleAnswer(string sql, List<SqlParameter> PList)
    {
        object obj = null;

        SqlConnection conn = new SqlConnection(connstr);

        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);

            if (PList != null)
            {
                foreach (SqlParameter p in PList)
                    cmd.Parameters.Add(p);
            }

            obj = cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            throw; // THIS LINE THROW THE NullReferenceException Error
        }
        finally
        {
            conn.Close();
        }

        return obj;
    }
}

The problem is with using static connection string field inside static classes. So, is there any way to solve this issue without using any non static public classes?

Updated:

Please notice the following:

  1. I don't want to use non-static methods, my question is how we can fix this using static methods.

  2. When we use static field, we initialize it right away:

    static string v1 = "hello";
    

    but why the initialization for the following code throw null before returning the actual connection string?

    static string connstr = ConfigurationManager.ConnectionStrings["DbSystem2018"].ConnectionString;
    

By the way, the connection string inside the web.config is fine.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
reaz
  • 735
  • 1
  • 10
  • 20
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) –  Jul 08 '18 at 19:00
  • i read this before, but as I mentioned , i don't want to use non static classes. what was explained in the link you sent is using non static classes. Thanks in advance. – reaz Jul 08 '18 at 19:02
  • Look at the exception and the diagnostic data it provides. The link in my 1st comment explains how to troubleshoot and diagnose those NullReferenceExceptions. –  Jul 08 '18 at 19:03
  • Possible duplicate of [Accessing Constants Static Class That References App Settings Config File](https://stackoverflow.com/questions/10606899/accessing-constants-static-class-that-references-app-settings-config-file) – GSerg Jul 08 '18 at 19:04
  • Please post the Exception. Or better, look what the exception says, which function is running into a null reference – dscham Jul 08 '18 at 19:04
  • @GSerg, according to the question, the exception happens inside the try-catch block. No App settings seem to be accessed within the try-catch block. –  Jul 08 '18 at 19:06
  • Your question doesn't make any sense now. First you say the exception happens within the try-catch (which you rethrow in the catch body), now with the edit at the end of your question you say the exception is caused by a code line outside the try-catch body. Which is it? –  Jul 08 '18 at 19:08
  • elgonzo: if i remove Throw in the catch block , it works fine. Also if I use non static methods, it works fine too. – reaz Jul 08 '18 at 19:08
  • @reaz of course it works fine if you catch the exeption and don't do anything with it. Exception is still there though. So, post the Exception. – dscham Jul 08 '18 at 19:09
  • Sens: 'The type initializer for 'BANKING.DataLayer.DataAccess' threw an exception.' NullReferenceException: Object reference not set to an instance of an object. – reaz Jul 08 '18 at 19:11
  • @reaz and there's no information about the line/function it was thrown in? – dscham Jul 08 '18 at 19:14
  • Sens: I only posted one function so the exact thrown part is : GetSingleAnswer() Catch block { Throw ; // The error thrown here } – reaz Jul 08 '18 at 19:15
  • @reaz Is this `ConfigurationManager.ConnectionStrings["DbSystem2018"].ConnectionString` static? – dscham Jul 08 '18 at 19:18
  • Sens: for some reason i tried to initialize a string field then use it inside a static class it works fine: Ex. static string v="Test"; // static field is initialized and there were no exception thrown public static class Test() { Set(v); } Catch (exception) { Throw; } – reaz Jul 08 '18 at 19:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174604/discussion-between-reaz-and-sens). – reaz Jul 08 '18 at 19:19
  • Remove the entire catch block, not just the throw statement. Now you can see where the exception is originally thrown. – Jonas Høgh Jul 08 '18 at 19:21

1 Answers1

3

This:

System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (config.ConnectionStrings.ConnectionStrings.Count > 0)
{
    var connString = config.ConnectionStrings.ConnectionStrings[nameOfConnectionString].ToString();
    return connString;
}

Is copy paste from: https://www.codeproject.com/Articles/1012286/Read-web-config-Settings

The problem is that you're accessing a config file. Those have to be converted to an object before they are accesible. This is what the code above does.

dscham
  • 547
  • 2
  • 10