473,788 Members | 2,721 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with array initialization using Activator.Creat eInstance

I'm building some dll assemblies that have in them the implementation of an
abstract class defined in a different assembly.

I'm trying to create objects of the type defined in the dlls with
"Activator.Crea teInstance".

Everything was working fine until I started to fill out the class def with
some implementation. At some point the CreateInstance was failing with a
"MissingMethodE xception - No parameterless constructor defined for this
object".

I tracked down the problem to an array I was creating in the implementation
of one of the methods.

Specifically, if I create my array like this:

byte [] myByteArray = {0xFF, 0xFF, 0xFF};

it will throw an exception. But, if I create it like this:

byte [] myByteArray = new byte[3];
myByteArray[0] = 0xFF;
etc.

It works fine.

I'm a bit puzzled by this. How can all function local code affect the
creation of an object? And why would it make a difference how the array is
created and initialized within a method of the derived class?

Can anyone help clear this up? Am I doing something I shouldn't be?

Thanks!
Nov 15 '05 #1
4 6715
Terry <ch**********@h otmail.com> wrote:
I'm a bit puzzled by this. How can all function local code affect the
creation of an object? And why would it make a difference how the array is
created and initialized within a method of the derived class?

Can anyone help clear this up? Am I doing something I shouldn't be?


<snip>

That sounds very odd to me. Could you provide a short but complete
example which demonstrates the problem?
See http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Ok. Here it is. Here's a simple test case which demonstrates the problem
I'm having. If I'm doing something wrong, please let me know.

There are 3 projects created. One is the "interface dll" which contains the
abstract class. Another is the "implementa tion dll" which contains a class
that derives from and implements the abstract class. And there's a Windows
forms app to use as the driver. Here are the steps and code.

1. Create a "Class library" project. This will define an abstract class to
act as an interface. Call it "InterfaceD ll".

Here is the code for the source file in this project. Compile it.

using System;
namespace InterfaceDll
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public abstract class TheInterface
{
public abstract int DoSomething1();
public abstract int DoSomething2();
}
}

2. Create another "Class library" project. Call it "Implementation Dll".
Add a project reference to the built "InterfaceD ll" you created in step one.
Here is the source for this one.

using System;
namespace ImplementationD ll
{
/// <summary>
/// Summary description for Class1.
/// </summary>
public class Implementation : InterfaceDll.Th eInterface
{
public Implementation( )
{
}
public override int DoSomething1()
{
//byte[] myBytes = {0xFF, 0xFF, 0xFF, 0xFF};
//foreach (byte b in myBytes)
//{
// Console.Write(b .ToString() );
//}
return 0;
}
public override int DoSomething2()
{
return 0;
}
}
}

* Note the lines commented out. Leave them commented out for now. Build
this dll.

3. Create a Windows forms app with a single button on the form. Add a
reference to the "InterfaceDll.d ll" built in step 1 to this project. Add a
click handler for the button. Add the following code to the button handler.

string strCurDir = Environment.Cur rentDirectory;
string filename = Path.Combine(st rCurDir, "implementation dll.dll" );
//Load the Assembly
Assembly a = Assembly.LoadFr om(filename);
// get all the types in the loaded assembly
Type[] types = a.GetTypes();
foreach (Type typ in types)
{
// dynamically create or activate(if exist) object
object obj = Activator.Creat eInstance(typ);
}

Build the forms app. Now, copy the "Implementation Dll.dll" from step 2 into
the "\bin\Debug " directory so the code can locate the assembly.

4. Run the windows forms app. Click the button. Note how it runs
properly.

5. Now, uncomment the code in the "DoSomethin g1" method in the
"Implementation Dll" project, build it and (DON'T FORGET) copy the new dll
into the same location as in step 3.

6. Run the windows forms app again. Click the button. It will throw an
exception on the "object obj = Activator.Creat eInstance(typ); " line.

"An unhandled exception of type 'System.Missing MethodException '
occurred in mscorlib.dll
Additional information: No parameterless constructor defined for
this object."

If you change the byte[] array allocation to use "new" instead of an
initializer list like the following, it works ok.

byte[] myBytes = new byte[4];
myBytes[0] = myBytes[1] = myBytes[2] = myBytes[3] = 0xFF;

Why does using an initializer for the byte[] array in the "DoSomethin g1"
method cause an error? Am I doing something wrong?

Thanks!

Terry

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
Terry <ch**********@h otmail.com> wrote:
I'm a bit puzzled by this. How can all function local code affect the
creation of an object? And why would it make a difference how the array is created and initialized within a method of the derived class?

Can anyone help clear this up? Am I doing something I shouldn't be?


<snip>

That sounds very odd to me. Could you provide a short but complete
example which demonstrates the problem?
See http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #3
Terry <ch**********@h otmail.com> wrote:
Ok. Here it is. Here's a simple test case which demonstrates the problem
I'm having. If I'm doing something wrong, please let me know.


<snip>

Brief request - I reckon it's generally easier to do this kind of thing
with console apps. In fact, you don't even need the three different
classes here. Here's a short class which demonstrates everything:

using System;
using System.Reflecti on;

class Test
{
public static void Main()
{
try
{
foreach (Type t in
Assembly.GetExe cutingAssembly( ).GetTypes())
{
Console.WriteLi ne (t.Name);
Activator.Creat eInstance (t);
}
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

public void Foo()
{
byte[] myBytes = {0xFF, 0xFF, 0xFF, 0xFF};
}
}
Even with the three-class system a console app would end up being
shorter to demonstrate with. Anyway, on with the problem itself.
You're iterating over *all* the types within the assembly - and the one
which is failing (at least on my system) is a type called:
<PrivateImpleme ntationDetails> (including the angle brackets).

If you compile the console app above and run it, you'll see the same
thing. Comment out the line in Foo and it runs fine. Comment out the
line using Activator.Creat eInstance instead, and you'll get something
like:

Test
<PrivateImpleme ntationDetails>
$$struct0x60000 02-1

Now, using Reflector (http://www.aisto.com/roeder/dotnet/) or ildasm
you can have a look and see that the struct is nested within
<PrivateImpleme ntationDetails> . I believe it basically contains the
initialisation data for the byte array. Add some more arrays and you'll
see the same thing, growing and growing. Look at mscorlib and there are
loads of them.

The upshot of this is that you should basically take more care about
which types you want to create instances of, although I agree it's a
somewhat surprising case. If you only look at public types (using
Type.IsPublic) you should be fine.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
Ah. I see. Thank you very much! You're a credit to the Internet! :-)

Terry

"Jon Skeet" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@news.microsof t.com...
Terry <ch**********@h otmail.com> wrote:
Ok. Here it is. Here's a simple test case which demonstrates the problem I'm having. If I'm doing something wrong, please let me know.


<snip>

Brief request - I reckon it's generally easier to do this kind of thing
with console apps. In fact, you don't even need the three different
classes here. Here's a short class which demonstrates everything:

using System;
using System.Reflecti on;

class Test
{
public static void Main()
{
try
{
foreach (Type t in
Assembly.GetExe cutingAssembly( ).GetTypes())
{
Console.WriteLi ne (t.Name);
Activator.Creat eInstance (t);
}
}
catch (Exception e)
{
Console.WriteLi ne (e);
}
}

public void Foo()
{
byte[] myBytes = {0xFF, 0xFF, 0xFF, 0xFF};
}
}
Even with the three-class system a console app would end up being
shorter to demonstrate with. Anyway, on with the problem itself.
You're iterating over *all* the types within the assembly - and the one
which is failing (at least on my system) is a type called:
<PrivateImpleme ntationDetails> (including the angle brackets).

If you compile the console app above and run it, you'll see the same
thing. Comment out the line in Foo and it runs fine. Comment out the
line using Activator.Creat eInstance instead, and you'll get something
like:

Test
<PrivateImpleme ntationDetails>
$$struct0x60000 02-1

Now, using Reflector (http://www.aisto.com/roeder/dotnet/) or ildasm
you can have a look and see that the struct is nested within
<PrivateImpleme ntationDetails> . I believe it basically contains the
initialisation data for the byte array. Add some more arrays and you'll
see the same thing, growing and growing. Look at mscorlib and there are
loads of them.

The upshot of this is that you should basically take more care about
which types you want to create instances of, although I agree it's a
somewhat surprising case. If you only look at public types (using
Type.IsPublic) you should be fine.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #5

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

Similar topics

0
5314
by: ka | last post by:
I'm implementing an IDesignerHost, for the CreateComponent method. The code below is quite standard. When loading a form, the CreateComponent works fine. However, when someone choose a control from the toolbox, the Activator couldn't create the component and returns null in CreateInstance. In what scenario, Activator.CreateInstance will be failed ?? I only create a System.Windows.Forms.Label. I've verified the type passed in is correct. ...
7
12036
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 a token into the instantiated class DBPassword and return a string; ************************************** namespace DBPasswordProvider public class DBPassword {
4
2721
by: Martin Maat | last post by:
Hi. I am using a COM component from managed code doing the following: Type type = Type.GetTypeFromCLSID(new Guid("B70FAAE6-4F85-480A-B1C5-DC9A6F175BFC"), serverMachineName, true); history = Activator.CreateInstance(type) as HistoryClass; This works on the local machine, no problem whatsoever. But when I run the client remotely, the cast in the second line of code shown above fails.
4
7676
by: garak | last post by:
Hi, I got the following problem : I have an defined an Array of different Actions: public PRootActions AllActions = new PRootActions ; I got a dynamic method where all Actions or other things like Materials are loaded from a Database to my Actions or Materials Array:
2
1879
by: Frank Pleyer via .NET 247 | last post by:
Hi, I got the following problem : I have an defined an Array of different Actions: public PRootActions AllActions = new PRootActions ; I got a dynamic method where all Actions or other things like Materials are loaded from a Database to my Actions or Materials Array: public void All_Db2Cl (Object AllData, ref int totalData)
3
12691
by: Doug Riley | last post by:
I am using CreateInstance to create an instance of a class and invoke a function of that class. I really need it to execute in a single line of code (long story, but I want to execute this code in the command window on demand, without declaring any variables). This code WORKS (but requires 2 lines of code and a variable declaration): Type typ = Type.GetTypeFromProgID("MyDLLx.clsMyClass"); Activator.CreateInstance(typ).mNoShow("Test");
6
1358
by: CreateObject | last post by:
Assume that I have the classes below; class mercedes: IAuto { .... } class ford: IAuto{ .... }
1
2837
by: learning | last post by:
Hi how can I instaltiate a class and call its method. the class has non default constructor. all examples i see only with class of defatul constructor. I am trying to pull the unit test out from the product source code, but still want to execute them under nunit. I am trying this idea on nunit sample source code. Here is my class and the experiemental code: both money.cs and Imoney.cs is compiled to cs_money.dll. then I create another...
11
3731
by: Matthew Wells | last post by:
Hello. I have figured out how to create an instance of an object only knowing the type by string. string sName = "MyClassName"; Type t = Type.GetType(sName); Object objNew = Activator.CreateInstance(t); This works, but now I need to declare an array like
0
9656
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
10177
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
10113
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,...
0
9969
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8995
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
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
5402
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5538
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4074
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.