473,805 Members | 2,007 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics and Reflection

I have a generic collection which I am using in classes to store a
collection of embedded objects.

Class Employee: IEntity
{
Private string mName;
Private int mEmployeeID;
….
Private GenericCollecti on<Address> mAddresses;

//property
Public GenericCollecti on<Address> Addresses
{
Get { return mAddresses; }
Set { mAddresses = value; }
}
}

Class Address: IEntity
{
Private string mStreetName;
Private string mCity;
…..
}

Now I am exposing one more property in the GenericCollecti on<T> class
which is “DeleteList”. In this list I store the all the objects (of type
T) which I might want to delete later.
GenericCollecti on<T>: CollectionBase
//I have tried inheriting from
System.Collecti ons.ObjectModel .Collection<T> also…
{
Private ArrayList mDeleteList;
//property
Public ArrayList DeleteList
{
get { return mDeleteList; }
}

}

I have another delete queue (this is different than DeleteList in
GenericCollecti on) that contains all the objects I marked for deletion.
Say I added an Employee object to this queue. Note that this queue can
hold different types of objects (Employee, Department etc).
So I pretty much rely on reflection in order to delete any of the
embedded object collection such as Addresses in Employee. Say “property”
is the property Addresses of the Employee class

PropertyInfo property = (PropertyInfo)m emberInfo;

//value is the instance of Employee class
Object propertyValue = property.GetVal ue(value, null);

Now how do I cast the propertyValue so I get the
GenericCollecti on<Address> list?
If I try this
foreach(IEntity entity in ((Collections.C ollectionBase)p ropertyValue)))
{
//Then I cannot get to the DeleteList property.
}

If I try this
foreach(IEntity entity in ((GenericCollec tion<IEntity>)p ropertyValue)))
{
//Then I get an exception which says it cannot convert a value of type
//GenericCollecti on<Address> to GenericCollecti on<IEntity>
}
Is there any other way I can cast the object easily?
I just want to implement a late delete scheme here which will allow me
to delete all the instances in one place, so I don’t have to take care
of this in each individual class that has embedded objects.
Thanks,
Uttara
Feb 14 '06 #1
1 6096
uttara wrote:
I have a generic collection which I am using in classes to store a
collection of embedded objects.

Class Employee: IEntity
{
Private string mName;
Private int mEmployeeID;
….
Private GenericCollecti on<Address> mAddresses;

//property
Public GenericCollecti on<Address> Addresses
{
Get { return mAddresses; }
Set { mAddresses = value; }
}
}

Class Address: IEntity
{
Private string mStreetName;
Private string mCity;
…..
}

Now I am exposing one more property in the GenericCollecti on<T> class
which is “DeleteList”. In this list I store the all the objects (of
type T) which I might want to delete later. GenericCollecti on<T>:
CollectionBase //I have tried inheriting from
System.Collecti ons.ObjectModel .Collection<T> also… { Private
ArrayList mDeleteList; //property
Public ArrayList DeleteList
{
get { return mDeleteList; }
}

}

I have another delete queue (this is different than DeleteList in
GenericCollecti on) that contains all the objects I marked for
deletion. Say I added an Employee object to this queue. Note that
this queue can hold different types of objects (Employee, Department
etc). So I pretty much rely on reflection in order to delete any of
the embedded object collection such as Addresses in Employee. Say
“property” is the property Addresses of the Employee class

PropertyInfo property = (PropertyInfo)m emberInfo;

//value is the instance of Employee class
Object propertyValue = property.GetVal ue(value, null);

Now how do I cast the propertyValue so I get the
GenericCollecti on<Address> list? If I try this
foreach(IEntity entity in
((Collections.C ollectionBase)p ropertyValue))) {
//Then I cannot get to the DeleteList property.
}

If I try this
foreach(IEntity entity in
((GenericCollec tion<IEntity>)p ropertyValue))) {
//Then I get an exception which says it cannot convert a value of
type //GenericCollecti on<Address> to GenericCollecti on<IEntity>
}
Is there any other way I can cast the object easily?
I just want to implement a late delete scheme here which will allow
me to delete all the instances in one place, so I don’t have to take
care of this in each individual class that has embedded objects.


First of all, don't overdo generics. Rule of thumb is that you should
be able to write your code without generics just fine and then change
the code so it uses reflection but stop at the point where the code
starts to get more complex than it was without generics.

I wouldn't inherit from CollectionBase, but from Collection<T>. Then
I'd implement an interface IEntityCollecti on on GenericCollecti on<T>.
IEntityCollecti on is an interface which exposes a NONgeneric list of
items to delete (or of type List<IEntity> )

So you can then simply retrieve the items to delete.

So, to use a generic class in code where you don't know the specific
type (thus the value of T), use an interface on the generic class to
access the data. Interfaces are also a way to write generic code, it's
just typed in a different way, and has the lovely side effect that it
makes your code more simpler, not more complex as generics CAN do
sometimes.

FB

--
------------------------------------------------------------------------
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Feb 15 '06 #2

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

Similar topics

1
2136
by: andrew queisser | last post by:
I've been trying to dynamically create a class DevT that's derived from a generic base GenBase<T>. It doesn't seem to work. I'm attaching a code sample below that illustrates the problem. CreateType() fails when the base class is a parametrized class, as in DevT : GenBase<int>. CreateType() works if the base class is not parametrized, even if the base of the base was parametrized, as in DevT : GenBaseInt : GenBase<int>
7
3514
by: Gene Vital | last post by:
Hi all, I need some help in understanding how to use Generics. I have a class based on a user control that can be put on any Container at runtime, I want to be able to call a method on the parent class without knowing the type of the parent class, can this be done with C#? I thought this was what Generics was supposed to be all about but I have spent the whole day Googling and I can't find a way to do this in C#.
9
5988
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
1
2440
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes "ThrowInConstructor" and "ThrowInFoo". First one throws "MyOwnException" in constructor, second one in "Foo()" method. There is a "GenericCatch" generics class able to accept "ThrowInConstructor" and "ThrowInFoo" as type parameter "<T>". There are two methods in...
4
2821
by: Cedric Rogers | last post by:
I wasn't sure if I could do this. I believe I am stretching the capability of what generics can do for me but here goes. I have a generic delegate defined as public delegate bool RuleDelegate<T>(T item); In my class my goal is to use a generic list collection to contain my generic delegates. This will allow me to pass this List to another library and call this list of functions. This could provide a new way to build rule base...
5
1651
by: Wiktor Zychla [C# MVP] | last post by:
suppose I have a class class MyContainter { List<something1list1; List<something2list2; ... List<somethingnlistn; othertype1 otherfield1; ...
10
2246
by: Marc Gravell | last post by:
Given a generic method "of T", is there a good way of ensuring that any static ctor on T has executed? Following code demonstrates (TestClass1) that via generics you can use the Type instance long before the static ctor fires. With a generic class and the "new()" clause, I can force this in the static ctor of the generic class, but this is not always convenient, plus may (possibly?) be seen as a no-op . Sample; ideally I'd get "Static...
7
6357
by: =?Utf-8?B?TXJOb2JvZHk=?= | last post by:
Say I have a class that has a generics List as follows: public List<MyClassmyClassList = new List<MyClass>(); and I want to create another class which tries to add an element of MyClass to that list, but it is not explicitly creating an instance of MyClass, but instead using the Activator to create an instance based on it's type name. How can I accomplish this in C# using reflection?
8
1474
by: Tony Johansson | last post by:
Hello! I have read that in practice, casting proved to be several times faster than using a generic. So the main reason to use generics is not that the performance is better because that's not the case. The only reason is that it's type-safe. I must ask if anyone has made any significant performance improvement using
0
9716
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10604
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10356
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10361
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7644
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6874
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5676
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3839
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.