D
Daniel Ervi
Hi All,
I have a question for the group as I can't seem to come up with any
suitable solutions. I'm not that new to programming or C#, but
neither am I very fluent yet, so I'd appreciate any help at mastering
my craft.
What I am trying to do is best illustrated in code:
public class TBase
{
public static HashTable itemCache = new Hashtable();
}
public class TItem : TBase
{
private string name;
private TItem()
{
// Disable default constructor
}
public TItem(string ItemKey)
{
// Check cache first
if (itemCache.ContainsKey(ItemKey))
{
// I know this isn't possible!
this = (TItem)itemCache[ItemKey];
}
// Not in cache so retrieve it from external source
else
{
this.name = "whatever"
// ... do expensive data loading routine
itemCache.Add(this.name, this);
}
}
}
TItem myItem = new TItem("ABC"); // Loaded from external
source
TItem myCachedItem = new TItem("ABC"); // Should be loaded from
cache
I know what I am asking for is a variation of a Factory pattern, but I
would like to keep the standard C# syntax. A factory pattern would
disable the default constructor and then use a custom static
constructor to return the object from the cache. I can do this, but
it deviates from the standard C# syntax. Ideally I'd like to overload
the new operator, but C# can't do this.
I guess my question can be summarized as what is the best way to
replace the "this" reference with an already constructed Item,
retrieved from the cache, while still using new?
Thanks for any advice!
Daniel
I have a question for the group as I can't seem to come up with any
suitable solutions. I'm not that new to programming or C#, but
neither am I very fluent yet, so I'd appreciate any help at mastering
my craft.
What I am trying to do is best illustrated in code:
public class TBase
{
public static HashTable itemCache = new Hashtable();
}
public class TItem : TBase
{
private string name;
private TItem()
{
// Disable default constructor
}
public TItem(string ItemKey)
{
// Check cache first
if (itemCache.ContainsKey(ItemKey))
{
// I know this isn't possible!
this = (TItem)itemCache[ItemKey];
}
// Not in cache so retrieve it from external source
else
{
this.name = "whatever"
// ... do expensive data loading routine
itemCache.Add(this.name, this);
}
}
}
TItem myItem = new TItem("ABC"); // Loaded from external
source
TItem myCachedItem = new TItem("ABC"); // Should be loaded from
cache
I know what I am asking for is a variation of a Factory pattern, but I
would like to keep the standard C# syntax. A factory pattern would
disable the default constructor and then use a custom static
constructor to return the object from the cache. I can do this, but
it deviates from the standard C# syntax. Ideally I'd like to overload
the new operator, but C# can't do this.
I guess my question can be summarized as what is the best way to
replace the "this" reference with an already constructed Item,
retrieved from the cache, while still using new?
Thanks for any advice!
Daniel