I am not certain if I understand the issue here correctly so please feel
free to tell me I am missing the point. It seems to me that there are two
separate issues involved. One is easy to solve, the other is a bit more
complex.
First the easy one: This code needs to work with an arbitrary set of
classes, but needs to treat them as if they were the same kind of class
(i.e. perform the same operations on the same members of each class). If
you have control of the implementation each of these arbitrary classes, why
not do one of the following? Define an interface containing someProperty
and anotherProperty and then have each class to be handled by this code
implement that interface. Alternately, define a class that implements these
members and then derive all you other classes from it. This is more
limiting but even better code reuse, if all the classes have a common
implementation for the common members .
The second problem I see is the need to instantiate new instances of the
arbitrary class within the utility function. Since you have no way of
knowing ahead of time what class will need to be instantiated, this is an
apparent issue. To solve it, I would add a GetNewInstance( ) method to my
interface above. Then I would pass into this routine an exemplary instance
of the class it needs to be creating. Each time a new instance of the class
is needed, it calls GetNewInstance on the exemplar instance. In this way
GetNewInstance is acting as a call back function. The GetNewInstance( )
method of the exemplar will always create a new instance of the correct
class but should return it under the guise of the common interface. There
are variations on this solution. Is myHash handed into the routine from
outside? If so, a set of custom hashtable classes that implement the
GetNewInstance member or equivalent might be better way of implementing the
call back function.
Anyway, I hope this helps.
--Ken
Does this help? It
"ITnerd" <no**@nunyabidn ess.com> wrote in message
news:mv******** ************@co mcast.com...
In the interest of code re-use, I would like to place some code in a
utility class to be used by other classes. The problem is that this code requires
the following snippet:
for(i=0; i < tbl.Rows.Count; i++)
{
myDataRow = tbl.Rows[i];
company.someNes tedClass sc = new company.someNes tedClass();
for(j=0; j < tbl.Columns.Cou nt; j++)
{
sc.someProperty = Convert.ToBoole an(myDataRow.It emArray[0]);
sc.anotherPrope rty = Convert.ToBoole an(myDataRow.It emArray[1]);
}
myHash.Add(some Key, sc);
}
how can I make company.someNes tedClass sc = new company.someNes tedClass();
into something more generic/variable/unspecific?
Also, can you cast to a cast variable of some sort, so that you don't have
to know, until runtime, what you want to cast to?
As it is, I have to put this code in every class I wish to apply it to.
Thanks in advance.