473,549 Members | 2,545 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to fill a generics List with reflection?

Say I have a class that has a generics List as follows:

public List<MyClassmyC lassList = 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?

Jun 27 '08 #1
7 6325
On May 13, 2:30*pm, MrNobody <MrNob...@discu ssions.microsof t.com>
wrote:
Say I have a class that has a generics List as follows:

public List<MyClassmyC lassList = 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?
I don't see where is the problem, you can invoke your Add either by
reflection or simply casting the instance resulting of using Activator
to the correct type.
Or you can use Activator to create an instance of MyClass and then use
InvokeMember with the created instance
Jun 27 '08 #2
On Tue, 13 May 2008 11:30:00 -0700, MrNobody
<Mr******@discu ssions.microsof t.comwrote:
Say I have a class that has a generics List as follows:

public List<MyClassmyC lassList = 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?
Well, you said you're already using Activator. So isn't that using
reflection?

Once you've got an instance of MyClass, it doesn't matter how you got it..
You can add it to a List<MyClasswhe ther you used "new" or Activator.
So, if you're having problems adding the instance to your list, it's
because you're not creating the type you apparently think you are.

You should post a concise-but-complete code sample that demonstrates the
problem you're having. Make sure you're specific about what fails.

Pete
Jun 27 '08 #3


"Peter Duniho" wrote:
>
You should post a concise-but-complete code sample that demonstrates the
problem you're having. Make sure you're specific about what fails.

Pete
Ok, here is a good test case to demonstrate what I am talking about:

public class MainClass
{
public void Test()
{
ParentClass parent = new ParentClass();
Console.WriteLi ne(parent.myCla ssList.Count + " items");

Type listType = Type.GetType("T ools.MyClass");
List<listTypeli st = parent.GetType( ).GetField("myC lassList");
// the type or namespace name 'listType' could not be found
list.Add(Activa tor.CreateInsta nce(listType)); // compiler error:
cannot convert form object to 'listType'

Console.WriteLi ne(parent.myCla ssList.Count + " items");

}
}

public class ParentClass
{
public List<MyClassmyC lassList = new List<MyClass>() ;
}

public class MyClass
{
public string testString = "";
}

See how do I make a generic reference of that List? I think in Java you can
do something like List<?so you dont need to explicitly specify type but I
cant figure out how to do it in C#.

See I need to get a reference to that List using reflection without
explicitly specifying it's type, since it's type could be anything. Then I
need to add a new instance of that type to the list, again without explicitly
specifying it's type.

It has to be completely dynamic so that I can create an instance of a user
specified type and Add it to a List of that type.
Jun 27 '08 #4
On Tue, 13 May 2008 12:39:01 -0700, MrNobody
<Mr******@discu ssions.microsof t.comwrote:
[...]
See how do I make a generic reference of that List? I think in Java you
can
do something like List<?so you dont need to explicitly specify type
but I
cant figure out how to do it in C#.
I don't think you can do this in Java either. "List<?>" is sort of like
"List<T>" in C# where T is a type parameter, but in either case it's a
compile-time thing used to declare a generic. When you _use_ a generic,
there has to be a real type there.

Do you really need your collection to be in a List<T>? Again, since the
main benefit of generics is a compile-time thing, if you don't know the
type at compile time, it's not clear why you want to use List<T>.

In this particular example, I would just use an ArrayList, which is an
untyped collection that otherwise behaves similar to List<T>.

If you think that you really need a List<There, it would be helpful if
you could elaborate on that, including presenting a code example that
actually demonstrates that requirement. To do what you're asking
literally I believe would at a minimum require using reflection again,
instantiating the specific List<Tusing Activator or similar, and then
using reflection to invoke the appropriate Add() method.

But it seems to me that there's a strong likelihood that there's not
really a literal need to use List<T>. If you can provide a better
question, it's like you'll get a better answer, including an explanation
of an alternative approach that doesn't require reflection at all for the
collection itself.

Pete
Jun 27 '08 #5
MrNobody wrote:
See how do I make a generic reference of that List? I think in Java you can
do something like List<?so you dont need to explicitly specify type but I
cant figure out how to do it in C#.
List<T>. From your description I don't even think you need reflection.

Something like:

private void AddNewTolist<T> (List<TtoList)
{
if (toList != null)
toList.Add(new T());
}

Maybe I'm wrong, I don't have access to VS atm.

Chris.
Jun 27 '08 #6
Generics:

public void Test()
{
ParentClass parent = new ParentClass();
Console.WriteLi ne(parent.myCla ssList.Count + " items");
Foo(parent.myCl assList);
Console.WriteLi ne(parent.myCla ssList.Count + " items");
}
public void Foo<T>(List<Tli st) where T : new() {
list.Add(new T());
}

Marc
Jun 27 '08 #7
MrNobody <Mr******@discu ssions.microsof t.comwrote:
You should post a concise-but-complete code sample that demonstrates the
problem you're having. Make sure you're specific about what fails.

Ok, here is a good test case to demonstrate what I am talking about:
<snip>

Looks to me like ParentClass should be generic, at which point half the
problems go away.

Most of the point of generics is to give *compile-time* type safety. If
you're not going to get that benefit, you'll probably find it's easier
just to use ArrayList rather than messing around with reflection.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #8

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

Similar topics

2
2867
by: Marc | last post by:
Given a class 'Invoice' with a property 'public IMyColl<IInvoiceLine> InvoiceLines' where 'IMyColl<T> : IList<T>' i would like to detect by reflection that 'InvoiceLines' is a 'System.Collection.Generic.IList'. When performing something like: 'if (typeof(IList<>).IsAssignableFrom(propertyInfo.Type))' where 'propertyInfo' obviously refers to...
4
1551
by: Gazarsgo | last post by:
This seems to be a bit of a contradiction, but how can I construct a Generic class using a System.Type variable that is assigned at run time? Is there some parallel to the Generics concept that extends to having strictly-typed classes at run-time? I would gladly give up the compile-time errors if I could get rid of all these CType()s :)
1
6077
by: uttara | last post by:
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 GenericCollection<Address> mAddresses;
0
1207
by: Konrad Kaczanowski | last post by:
Hi all, I'm creating code generator for wrappers of some c# classes. With the introduction of c# 2.0 and generics the following problem arises. When encountering generic types anywhere inside the assembly, for example a generic method parameter declared as: System.Collections.Generic.List<int> the full name of that parameter type...
9
5961
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. ...
4
1294
by: cmay | last post by:
Is this something you are not allowed to do? I basically want to create an instance of a generic class where the type T is not know at compile time. e.g. dim s as System.Type = GetMyType() dim o as MyObj(Of s)
4
2797
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...
7
2194
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
4
2009
by: =?Utf-8?B?SGF5U2VlZA==?= | last post by:
Is there some way to use Generics in dynamic code using the Type.GetType("MyClassName") as an argument? List<Type.GetType("MyClassName") oList = new List<Type.GetType("MyClassName") > .... or is there a way to declare a generic using strings that hold class
0
7526
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...
0
7457
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
6051
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5375
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...
0
5092
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...
0
3504
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3487
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
771
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...

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.