Designart
Designart

Reputation: 3

Update a value outside a class and keep it alive in C#?

Well I struggle with a basical scope problem (in my opinion), I'd like to update my variable solution from outside and keep it alive (in the class CProperties) to pass it in my dictionnary so I keep the same key for different value.

ps : I must keep a Dictionary<string, string>() format (for an Api) (yes I would prefer string, string[])

pps: I come from C++

What's would be the right way to do this ?

public static class CProperties
{
   public static string solution { get; set; }
            
   static public Dictionary<string, string> product = new Dictionary<string, string>()
   {
       { "product_name", solution}
   };
}
static void mycrazyFunc()
{   
            // I skip the Database connection and everything
            DataTable dt = new DataTable();
            dt.Load(cmd.ExecuteReader());
        
             if (dt.Rows.Count > 0)
             {
                 foreach (DataRow rows in dt.Rows)
                 {
                     dynamic JsonObj = new ExpandoObject();
            
                     if (!string.IsNullOrEmpty(rows["Product"].ToString()))
                     {
                        CProperties.solution = rows["Product"].ToString(); // Got the value !
                        JsonObj.custom_fields = CProperties.product;       // Lost the value ! 
                                                                           // {"product_name", "null"}
                     }
                 }
             }
}

Upvotes: 0

Views: 145

Answers (1)

Jamiec
Jamiec

Reputation: 136074

Have the setter and getter read/write to/from the dictionary itself:

public static class CProperties
{
   public static string solution 
   { 
     get{ return product["product_name"]; }
     set{ product["product_name"] = value; }
   }
            
   static public Dictionary<string, string> product = new Dictionary<string, string>()
   {
       { "product_name", null}
   };
}

or have the dictionary built on demand

public static class CProperties
{
   public static string solution { get; set; }
            
   static public Dictionary<string, string> product => new Dictionary<string, string>()
   {
       { "product_name", solution}
   };
}

Either will work for you.


But all that aside, your question was

What's would be the right way to do this ?

Arguably the right way to do this is get rid of CProperties altogether as it serves no real purpose and just set the dictionary directly:

JsonObj.custom_fields = new Dictionary<string,string>{ 
       ["product_name"] = rows["Product"].ToString() 
};

Upvotes: 3

Related Questions