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

  • Thread starter Thread starter Carl Rosenberger
  • Start date Start date
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
 
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.
 
Back
Top