c# - Where/when to populate lookup values? -


i've tried googling 2 days can't seem find answer.

i'd category class provide description based on id entered , return error if id not valid. best approach?

public class category {     private int _id;     private string _desc;      public category(int id)     {         id = id;     }      public int id      {                  {             return _id;         }          set          {             _id = value;              //_desc = value data access layer or throw error if id invalid                        }     }      public string description      {                  {             return _desc;         }            } }  public class person {     public int id {get; set;}      public category category {get; set;} }  public class myapp {     static void main()     {         person p = new person();          category c = new category(2);          p.category = c;     } } 

since there potentially several instances of class category, waste memory-wise include values in class itself. instead should accessed elsewhere. instance static function in class.

public class categoryhelper {     public static string getcategorydesc(int catgeoryid)     {         ...access database description     } } 

which use in description getter in category class:

public string description  {          {         return categoryhelper.getcategorydesc(this.id);     }        } 

now, since have getcategorydesc in separate class can optimize performance. instance, if values lookup won't change duration of run can cache descriptions in memory avoid db trips. in following code call db first time call made , the results cached. called "memoization".

public class categoryhelper {     dictionary<int,string> cacheddesc; //dictionary used store descriptions     public static string getcategorydesc(int catgeoryid)     {         if (cacheddesc==null) cacheddesc = new dictionary<int,string>(); // instatiate dictionary first time         if(cacheddesc.containskey(catgeoryid)) //we check see if have cached value before         {             return cacheddesc[catgeoryid];         }         else         {             var description = .... value db             cacheddesc.add(catgeoryid, description); //store value later use             return description;         }     } } 

you can make simpler , more complex, , since isolated in own function have little no changes elsewhere.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -