I am trying to write a method that "tries again" when some Database (SQL-Server) related stuff fails the first time. After the job is done (or failed), the given connection should be closed.
But in the finally block the connection-object stays NULL, shouldn't there be a reference to the callers Connection-object? I tried a non-static aproach aswell with the same results.
Why is connection (in KeepTrying::Run) always null?
Here is simplified code:
using System;
using System.Data.SqlClient;
class Program
{
    static void Main(string[] args)
    {
        DBManager.CreateConnection();
        Console.ReadKey();
    }
}
public static class DBManager
{
    public static SqlConnection Connection;
    public static bool CreateConnection()
    {
        String error = String.Empty;
        bool result = KeepTrying.Run(() => _CreateConntection(), Connection, out error);
        return result;
    }
    private static bool _CreateConntection()
    {
        Connection = new SqlConnection("Data Source=SERVERNAME;Initial Catalog=DATABASENAME;user=USER;password=PASSWORD;");
        Connection.Open();
        return true;
    }
}
public static class KeepTrying
{
    public static T Run<T>(Func<T> method, SqlConnection connection, out String ErrorMessage)
    {
        ErrorMessage = String.Empty;
        int maxAttempts = 3;
        int time = 435;
        int attempts = 0;
        bool error = true;
        while (error && attempts < maxAttempts)
        {
            attempts++;
            try
            {
                T result = method();
                return result;
            }
            catch (Exception ee)
            {
                ErrorMessage = ee.Message;
                error = true;
                if (attempts < maxAttempts)
                    System.Threading.Thread.Sleep(time);
                else
                    return default(T);
            }
            finally
            {
                if (connection != null)  //connection is still null here
                    connection.Close();
            }
        }
        return default(T);
    }
}
 
    