C# using reflection to create a struct

c#, reflection

Solution

If the values are structs, they're likely to be immutable - so you don't want to call a parameterless constructor, but the one which takes the appropriate values as constructor arguments.

If the structs aren't immutable, then run away from them as fast as possible, if you can... but if you absolutely have to do this, then use `Activator.CreateInstance(SomeClass)`. You'll have to be very careful when you use reflection to set properties or fields on the value type though - without that care, you'll end up creating a copy, changing the value on that copy, and then throwing it away. I suspect that if you work with a boxed version throughout, you'll be okay:

using System;

// Mutable structs - just say no...
public struct Foo
{
    public string Text { get; set; }
}

public class Test
{
    static void Main()
    {
        Type type = typeof(Foo);

        object value = Activator.CreateInstance(type);
        var property = type.GetProperty("Text");
        property.SetValue(value, "hello", null);

        Foo foo = (Foo) value;
        Console.WriteLine(foo.Text);
    }
}

Problem

I am currently writing some code to save general objects to XML using reflection in c#. The problem is when reading the XML back in some of the objects are structs and I can't work out how to initialise the struct. For a class I can use ``` ConstructorInfo constructor = SomeClass.GetConstructor(Type.EmptyTypes); ``` however, for a struct, there is no constructor which takes no parameters so the above code sets constructor to null. I also tried ``` SomeStruct.TypeInitializer.Invoke(null) ``` but this throws a memberaccessexception. Google gives no promising hits. Any help would be appreciated.

Original source