Question

I'm trying to get a Byte[] using reflection. Unfortunately the result it always NULL. The property is filled with data. Here's my code snippet.

public static void SaveFile(BusinessObject document)
{
    Type boType = document.GetType();
    PropertyInfo[] propertyInfo = boType.GetProperties();
    Object obj = Activator.CreateInstance(boType);
    foreach (PropertyInfo item in propertyInfo)
    {
        Type xy = item.PropertyType;
        if (String.Equals(item.Name, "Content") && (item.PropertyType == typeof(Byte[])))
        {
            Byte[] content = item.GetValue(obj, null) as Byte[];
        }
    }
    return true;
}

Here's the working code:

    public static void SaveFile(BusinessObject document)
{
    Type boType = document.GetType();
    PropertyInfo[] propertyInfo = boType.GetProperties();
    foreach (PropertyInfo item in propertyInfo)
    {
        if (String.Equals(item.Name, "Content") && (item.PropertyType == typeof(Byte[])))
        {
            Byte[] content = item.GetValue(document, null) as Byte[];
        }
    }
}
Was it helpful?

Solution

Your code looks strange. You are creating a new instance of the type of the parameter and try to get the value from that instance. You should be using the parameter itself instead:

public static void SaveFile(BusinessObject document)
{
    Type boType = document.GetType();
    PropertyInfo[] propertyInfo = boType.GetProperties();
    foreach (PropertyInfo item in propertyInfo)
    {
        Type xy = item.PropertyType;
        if (String.Equals(item.Name, "Content") &&
            (item.PropertyType == typeof(Byte[])))
        {
            Byte[] content = item.GetValue(document, null) as Byte[];
        }
    }
}

BTW:

  1. return true in a method that returns void is illegal and will lead to a compiler error.
  2. There is no need to use reflection in your case. You could simply write this:

    public static void SaveFile(BusinessObject document)
    {
        Byte[] content = document.Content;
        // do something with content.
    }
    

    This is only true if Content is defined on BusinessObject and not only on derived classes.

OTHER TIPS

from your code snippet it appears you are not populating any value.

Object obj = Activator.CreateInstance(boType); 

this would just invoke the default consturctor and assign default values for all types. and for byte[] it is null

it should be

item.GetValue(document, null)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top