public class Form
{
internal static Dictionary<string, Form> Cache = new
Dictionary<string, Form>();
public string FormID{get;set;} = string.Empty;
public Form()
{
if (!Cache.ContainsKey(FormID))
Cache.Add(FormID, new Form());
// exception here because new Form() is always called again
}
}
I want to create instance of object of class Form inside Cache. if Cache contains the FormID property then nothing will happened to static dictionary Cache.
Cache must hold single instance for each instance from Form that have unique FormID. this mean each Form instance has instance inside a Cache with same FormID. so creating new instances from cloning the cache will be fast. thats what i need to do.
Camilo Terevinto answered it good below.
This code doesn't make sense:
if (!Cache.ContainsKey(FormID))
Cache.Add(FormID, new Form());
You would always be checking/adding the default value of FormId
. With that, you would ever only have a single key/value pair in that Dictionary, so using a Dictionary would be a waste.
You should use a factory method for this, and leave the default constructor alone:
private Form()
{
}
public static Form BuildForm(string formId)
{
if (!Cache.ContainsKey(formId))
{
Cache.Add(formId, new Form());
}
return Cache[formId].DeepClone(); // using DeepCloner extension
}