Thursday, March 22, 2012

Trouble with generics :-)

I am continuously runnign into some troubly with generics and I would love to know whether I have overlooked something.
First item: How can I declare a variable of an untyped generic type?
Let's take the following type:

publicabstractclassValidation<T>where T :class,IValidatable

I utilize subclasses of Validation<T> to validate specific information. So, SomeValidation may inherit from Validation<Field>, for example.
Is there any way to declare a variable of the Validation<T> type, without type parameter, so that I can hold any validation I like?
Second item: type identity
I get all validations by enumerating all types in the assembly- has something to do with ease of maintenance. Now, in the loop.

foreach (Type typein assembly.GetTypes ()) {

I need to throw out all types that are not subtypes of Validation<T>. How do I reference the generic type? typeof does not work. Right now I do ugly tricks that go like this:
* Validation<T> inherits from Validation.
* So I can easily check whether a type is a subtype of Validation

if (type ==typeof (Validation)) {

continue;

}

* And then I compare strings.

if (type.FullName =="EntityBroker.Sdk.XmlSchema.Validations.Validation`1") {

continue;

}

I do NOT like the string comparison - if I rename the class, it blows without the compiler telling me. But I was just totally unable to find a way to get the type for a type reference.
Anyone ideas for this?

Try this link it explains it, you are back in explict casting land. Hope this helps.
http://www.c-sharpcorner.com/Code/2004/March/NewCSharpFeaturesP1.asp
Thanks for your answer.
Sadly it was useless. Actually it had ZERO relevance to th specific questions asked.


This code is from the link below. Hope this helps.

public T GetPlugin< T>() where T : IPlugin
{
foreach (IPlugin plugin in _manager)
{
if (plugin.GetType().GetInterface(typeof(T).FullName) != null)
{
return (T)plugin;
}
}

return default(T);

http://msdn.labtech.epitech.net/Blogs/jaylee/archive/2005/03/16/2497.aspx


Generics no take a look at the predicates.
http://pluralsight.com/blogs/dbox/archive/2005/04/24/7690.aspx

0 comments:

Post a Comment