473,396 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Writing to "this", or a general OOP question I guess...

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
Nov 16 '05 #1
7 1570
RCS
You are so close, you don't even know!! Should I give it away???

You want the Singleton Pattern - does exactly what are you looking for. It
will only create an instance of your class the first time, then every other
call to New will re-use the original instance of the class. Right??

I don't have any good examples handy, do a search, lots of examples on the
web. Post back if you can't find any good ones. Good luck!
"Daniel Ervi" <ac*@neural101.net> wrote in message
news:87**************************@posting.google.c om...
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

Nov 16 '05 #2
I have two answers to your question.

First, there isn't any way to do what you want to do. By the time the
constructor is called (in C#, C++, VB.NET, ... ) memory for the object
has already been allocated in a different place than the memory that
the object in the hash occupies, so there is no way to "return" the
object that you've stored away. The constructor's job is just to fill
in the already allocated memory; it can't change the location (and thus
the reference identity) of the object.

That said, the key statement you made is wrong... or at least off base.
Using a static method to return the object instance does not "deviate
from the standard C# syntax" _for a factory pattern_. Even if you could
find some way to get the effect you want, your factory would be
different from every other factory out there written in C#, and so
would be difficult to maintain.

Yes, in C++ you can override "new" and create an "invisible object
factory," but in C# the standard syntax is to use a static method. It's
what most of us are doing and what anyone coming along after you
looking at your code will recognize.

Nov 16 '05 #3
RCS wrote:
You want the Singleton Pattern - does exactly what are you looking for. It
will only create an instance of your class the first time, then every other
call to New will re-use the original instance of the class. Right??


He doesn't need the Sigleton Pattern, but the Builder Pattern.

Till
Nov 16 '05 #4
While your argument about using a static method for the factory pattern
is true, it is indeed possible to assign to this if that particular
type is a struct (value type). If you look at the ECMA standard, it
says that for structs, "this" is a variable, not a value and hence can
be assigned to (like an out/ref parameter).

Regards
Senthil

Nov 16 '05 #5
ace
RCS:

Thanks for the advice on the Singleton Pattern. I'm not sure it is the
right match for me though as I need multiple instances (ie: "ABC",
"BCD", etc) of the TItem class. It may apply here though, and I'll
have to think about it a little more.

Bruce:

I didn't mean to imply that the Factory Pattern syntax deviated from
the C# standard, but in hindsight I see that's how I described it.

A little more detail may help. I'm working on a class framework which
has a large number of classes available to the programmer. My goal in
the TItem example was to convey that I want to have multiple instances,
but none with a duplicate ItemKey. For effeciency I want to have a
global cache operating beneath all the objects to apply transparent
caching to the end users of the framework. I'd like to retain the
"new" syntax simply because it is consistent with the rest of the
objects in the framework, and it might be akward for me to have only
one or two classes using the different factory-style syntax.

I feel that I'm close to a solution, but I just can't seem to work it
out in my head yet, hence my post looking for a fresh perspective. In
any case, thanks for taking the time to offer your thoughts!

Till:

I have to admit that I am a complete design patterns newbie, having
acquired two books on them less than a week ago! I haven't covered the
Builder Pattern yet, but will brush up on it and see if it will help.
Thanks for the tip!

Daniel

Nov 16 '05 #6
True, but structs are copied in many situations: when they're assigned,
when they're passed as arguments, etc, so the OP's goal of having "only
one of each type" in memory at any one time (where "type" is determined
by some key) cannot be achieved using structs.

Nov 16 '05 #7
Hmmm. I see your problem, but I see no way around it.

The "new" operator allocates memory for the object instance and then
passes control to your constructor. I see no way to intervene in that
process (as you can in C++) in order to have the result of "new" be
anything other than the memory allocated by that "new" operation by the
runtime.

As well, the .NET Framework itself uses static methods to return "new"
objects here and there (in precisely this sort of situation), so if you
did have a few classes that instantiated themselves this way it would
not be an unfamiliar paradigm for your users.

Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Ernst Murnleitner | last post by:
Dear Readers, Is it possible to forbid conversion from this or use of this in general except where it is explicitly wanted? Reason: I changed my program from using normal pointers to...
1
by: PeteCresswell | last post by:
I'm working on a new report in an MS Access DB. The first anomaly was a message "This action will reset the current code in break mode." when the report was run. Seems TB something about my...
7
by: relient | last post by:
Question: Why can't you access a private inherited field from a base class in a derived class? I have a *theory* of how this works, of which, I'm not completely sure of but makes logical sense to...
60
by: Dave | last post by:
I'm never quite sure whether to use "this." or not when referring to fields or properties in the same class. It obviously works just fine without it but sometimes I wonder if using this....
2
by: Bryan | last post by:
Hello all, Can anyone explain when one should use the "document" object and when one should use the "this" object? Also, is the "self" object the same as the "document" or "this" object?
14
by: srinivas | last post by:
hi, i am incrementing a list iterator "m_item" in my .cpp file m_item._ptr->_next is showing the valid item. but in the library overloaded function for ++ 1 >_Myt_iter operator++(int) 2...
2
by: =?Utf-8?B?bWFlbGJl?= | last post by:
For the last few days, 5 to be exact, I have received a popup window when I have turned on my computer. The message in the popup says "This OS is not supported." I got a virus via MSN about a week...
7
by: Joe | last post by:
usually slide bars move by "jumps" while scrolling which looks not nice. I came accress slide bar with price menu, ewnt through script/web source code, and could not find anything that would case...
5
by: DamienS | last post by:
Hi, I have a static method in a class and I need to be able to return a reference to "this". Googling around, I found a heap of discussions of the pros/cons of "abstract static" etc. It was...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.