3

If I have the following byte array:

byte[] someArray = new byte { 0, 1, 2 };

and I want to copy it to an instance of a class through reflection, how can you do that?

// Inside a class method

PropertyInfo property = this.GetType().GetProperty("propertyName");

if(property.PropertyType == typeof(System.Byte[]))
{
    property.SetValue(this, ???, ???); // How to set an array?
} 

1 Answer 1

7

Use Array.Clone():

if(property.PropertyType == typeof(System.Byte[]))
{
    property.SetValue(this, someArray.Clone(), null); 
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Is the third parameter optional?
.NET 4.5 added an overload that takes only 2 parameters. I have added the third parameter to be backwards-compatible.
Great, thanks. I was wondering about the "pointer" and this takes care of it :)
The only thing to note is that the Array.Clone method is a shallow copy, so if you end up using reference types at some future point, the new array will point to the same objects that the original array did.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.