reusing an instance

  • Thread starter Thread starter Mariano Drago
  • Start date Start date
M

Mariano Drago

Hi there.
It will sound like a stupid question, but i cant figure out how to resolve
this...

Doing a little profiler job on the app im writing, i found a bottleneck in
some parts that involve DB access to retrieve User information.
Basically, i have an "User" class. The ctor of this class uses a method in
the data access layer. As you may figure it out, the method execs a SP and
pass the info back to the class, who load the data into the fields.

All going fine, works perfectly and, best of all, its in line with MS best
practices :)

So, to avoid constant access to the DB, and taking in consideration that the
maximun amount of users wont exced 80 i told to myself... WTF, i will take
all the records from the DB and store they in a static dataset!

With this in mind, i went into the adventure of writing an static method
that takes a UserID as the parameter and return a User instance!

This method will first hit the DB and retrieve all records (just do it
once), then create an instance of the User class for each record retrieved,
and store thats instances in an arraylist. Meanwhile, i write a new internal
ctor for the User class, which takes a datarow as the only parameter (this
ctor is only called by the static method) so now the User class dosent
access the DB anymore.

Finally, i rewrite the public ctor of User class (the old ctor hit the DB)
to retrieve the "instance" previously generated by the static method.
Something like:

static User Retrieve(int UserID)
{
search the static arraylist by index looking for UserID
return (User)(arraylist(index))
}

public class User
{
public User(int UserID)
{
this = retrieve(UserID) // ERROR
}
}

but i get a "Cannot assign to '<this>' because it is read-only"
.... do i miss a chapter... ??? Cant i reuse an instance???

The goal is to write something like:
User usr = retrieve(an userID)
Thanks in advance!
 
but i get a "Cannot assign to '<this>' because it is read-only"
... do i miss a chapter... ??? Cant i reuse an instance???

You can't change what "this" is a reference to, no. Instead, you should
make your static method public. This is called the factory pattern, by
the way.
 
Back
Top