Creating an instance of a no-constructor-struct with reflection

C

Carl Rosenberger

Hi all,

I would like to create an instance of a struct with
reflection.

The way I am used to doing this with classes:
- get a ConstructorInfo from the Type
- call Invoke()

However, if a struct does not have a constructor
declared, I don't get a single default constructor.
Here is a short code snippet that counts constructors:


using System;
using System.Reflection;

public class StructCreationWithReflection {

public static void Main(string[] args){
Type type = typeof(MyStruct);
ConstructorInfo[]cons = type.GetConstructors(
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance
);
Console.WriteLine(cons.Length);
}
}

public struct MyStruct{
public int foo;
}


Is there any other possibility to create a struct, if I
only have it's type during runtime?


If I add a constructor to a struct, there are no problems
and I can use reflection to create instances perfectly,
just the same as if I was using a class.


Has the reflection feature simply been forgotten for
no-constructor structs?


Thanks for any hints.


Kind regards,
Carl
 
J

Jon Skeet [C# MVP]

Carl Rosenberger said:
I would like to create an instance of a struct with
reflection.

The way I am used to doing this with classes:
- get a ConstructorInfo from the Type
- call Invoke()

However, if a struct does not have a constructor
declared, I don't get a single default constructor.

*All* structs have a parameterless constructor, implicitly. However, it
doesn't show up using reflection. You can create an instance with
Activator.CreateInstance though, and all the fields will be initialised
with their default values.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top