473,401 Members | 2,068 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,401 software developers and data experts.

Activator Question

My goal is to pass in an assembly and have the method return an
instance of any classes that inherit from the generic type T.

My problem is that I'm unable to cast from the result of
Activator.CreateInstance(curType) to T even though curType is a
concrete class of T (T is abstract in this case). I'm unsure why I
can't make this cast. In another method where I don't have the
restriction of T being a class, this approch works fine when T is an
interface.

I kind of feel like I'm going about this the wrong way, so if anyone
has suggestions on a better approach, please let me know :)

Thanks,
Dan

public static List<TGetClassesByClassName<T>(Assembly assembly,
object[] classParams) where T : class
{
List<Tret = new List<T>();

foreach (Type curType in assembly.GetTypes())
{

if (InheritsFrom(curType, typeof(T)) &&
curType.IsAbstract == false)
{
if (classParams == null)
{

ret.Add((T)Activator.CreateInstance(curType));
}
else
{

ret.Add((T)Activator.CreateInstance(curType, classParams));
}
}
}

return ret;
}
private static bool InheritsFrom(Type curType, Type targetType)
{
bool ret = false;

while (curType.FullName != "System.Object")
{
if (curType.FullName == targetType.FullName)
{
ret = true;
break;
}
else
{
curType = curType.BaseType;
}
}

return ret;
}

Aug 7 '07 #1
1 1400
On Aug 7, 4:53 pm, Dan Dorey <dandor...@gmail.comwrote:
My goal is to pass in an assembly and have the method return an
instance of any classes that inherit from the generic type T.

My problem is that I'm unable to cast from the result of
Activator.CreateInstance(curType) to T even though curType is a
concrete class of T (T is abstract in this case). I'm unsure why I
can't make this cast. In another method where I don't have the
restriction of T being a class, this approch works fine when T is an
interface.
Not too sure if this counts as good news or bad news but the code as
written works fine for me

I created a few classes. (The base is abstract and I included a 2
level inheiritance just for fun)

public abstract class Widget {
private string _name;
public Widget(string name) {
_name = name;
}

public string Name {
get { return _name; }
}

}

public class MyWidget : Widget {
public MyWidget(string name) : base(name) { }
}

public class MySecondWidget : Widget {
public MySecondWidget(string name) : base(name) { }
}

public class MyThirdWidget : MyWidget {
public MyThirdWidget(string name) : base(name) { }
}
And then created a list of them with

Assembly assem = Assembly.GetAssembly(typeof (Widget));

List<Widgetlist = NG.GetClassesByClassName<Widget>(assem,

new object[] {"A Name"});

I ended up with a list of 3 objects,

MyWidget,
MySecondWidget
MyThirdWidget

each initialized with "A Name".
All seems good. Are you getting a compile error or a runtime error?
NOTE:
You can replace InheritsFrom() with

typeof(T).IsAssignableFrom(curType)

e.g.
foreach (Type curType in assembly.GetTypes()) {
if (typeof(T).IsAssignableFrom(curType) &&
curType.IsAbstract == false) {
...
but I did that after testing the main functionality.

hth,
Alan.

Aug 8 '07 #2

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

Similar topics

18
by: David Sworder | last post by:
Hi, I need to design a method that creates and returns a large array of objects. The problem is that the *type* of object to create isn't know until runtime. As a result, a parameter of type...
7
by: hazz | last post by:
this is a repost with more concise code (well, for me) and better questions (I hope....) . given the following two classes, my intent is to use either Activator.CreateInstance or InvokeMember pass...
1
by: John Jenkins | last post by:
Hi, I have a fairly simeple question. What are the differences between Assembly.CreateInstance and System.Activator.CreateInstance? I had read that one maps to the other, however when I use...
3
by: System.Reflection Activator | last post by:
************************************** //Load the Assembly Assembly a = Assembly.LoadFrom(sAssembly); //Get Types so we can Identify the Interface. Type mytypes = a.GetTypes(); BindingFlags...
7
by: Ian Frawley | last post by:
Hi I have used the Activator class a number of times in my Windows apps and Windows Services and was thinking of using it again in one of my web services that I have been developing. I have been...
1
by: hazz | last post by:
this is a repost with a hopefully more clearly stated scenario and more concise questions at the end. given the following two classes, my intent is to use pass a token into the instantiated class...
1
by: Johnny R | last post by:
Hello, I'm loading a Class from Assemly DLL using Activator.CreateInstance. That loaded Class is executed in a worker Thread with no loop. What actually happends when class is loaded using...
0
by: Jules Winfield | last post by:
I have a singleton object that's accessed via remoting by way of Activator.GetObject(): SomeObject someObj=(SomeObject)Activator.GetObject(typeof(SomeObject),someUrl); My question is: Is the...
2
by: muriwai | last post by:
Hi, VC++ 2008 /clr: I have an unmanaged class: "class U" and managed one: "class ref M{ M( const U* ); }". In other words, the constructor of the managed class M takes the pointer to the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
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,...
0
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...

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.