Search code examples
c#sqltimeoutnullablegetter

How to use a getter with a nullable?


I am reading a bunch of queries from a database. I had an issue with the queries not closing, so I added a CommandTimeout. Now, the individual queries read from the config file each time they are run. How would I make the code cache the int from the config file only once using a static nullable and getter. I was thinking of doing something along the lines of:

static int? var;
get{ var = null;
    if (var.HasValue)
    ...(i dont know how to complete the rest)

My actual code:

private object QueryMethod(string item)
{
    using (SqlConnection connection = new SqlConnection(item))
    {
        connection.Open();

        using (SqlCommand sql = new SqlCommand())
        {
            AddSQLParms(sql);
            sql.CommandTimeout = 30;
            sql.CommandText = _cmdText;
            sql.Connection = connection;
            sql.CommandType = System.Data.CommandType.Text;

            sql.ExecuteNonQuery();
        }
        connection.Close();
    }
    return false;
}

Solution

  • var is a system keyword - don't use it

    V1 - in this version you expect config to have a value, otherwise error will occur

    static int? _timeout = null;
    
    private static int GetTimeout()
    {
        if (_timeout != null) return (int)_timeout;
        _timeout = GetTimeoutFromConfig();
        return (int)_timeout;
    }
    

    V2 - in this version you will use default value if config is empty

    static int? _timeout = null;
    private const int def_timeout = 120;   
    
    private static int GetTimeout()
    {
        if (_timeout != null) return (int)_timeout;
        int? to = GetTimeoutFromConfig();
        _timeout = (to ?? def_timeout); 
    
        return (int)_timeout;
    }
    

    converting from config

    private int? GetTimeoutFromConfig()
    {
        int val;
        bool converted = int.TryParse(ConfigurationManager.AppSettings["TimeoutValue"], out val);
    
        return (converted ? val : null);
    }