I have a console aplication where I am trying to obtain the values of the properties of an object dynamically:
class Program
{
static void Main(string[] args)
{
DtoCartaCompromiso test = new DtoCartaCompromiso() { CodProducto = 1,
DescProducto = "aaa",
CodProveedor = 2,
DescProveedor = "bbb",
FechaExpiracion = DateTime.Now,
FechaMaxEntrega = DateTime.Now,
NumLote = "22" };
var testlist = new List<DtoCartaCompromiso>();
testlist.Add(test);
List<Header> columns = new List<Header>() { new Header{Name= "CodProducto"},new Header{Name= "NumLote"},new Header{Name= "DescProducto"},new Header{Name= "CodProveedor"},new Header{Name= "DescProveedor"},new Header{Name= "FechaExpiracion"},new Header{Name= "FechaExpiracion"},new Header{Name= "FechaMaxEntrega"} };
foreach (var d in testlist)
{
foreach (var col in columns)
{
string value = ((d.GetType().GetProperty(col.Name).GetValue(d, null)) ?? "").ToString();
Console.WriteLine(value);
}
}
Console.Read();
}
}
public class DtoCartaCompromiso
{
public int CodProducto;
public string NumLote;
public string DescProducto;
public int CodProveedor;
public string DescProveedor;
public Nullable<DateTime> FechaExpiracion;
public Nullable<DateTime> FechaMaxEntrega;
}
public class Header
{
public string Name;
}
i am getting the error "Object reference not set to an instance of an object" when I get to the line:
string value = ((d.GetType().GetProperty(col.Name).GetValue(d, null)) ?? "").ToString();
the error seems to occur when I get to the GetProperty()
method, but I dont understand why
Your property is probably not public. Make it public or pass
System.Reflection.BindingFlags.NonPublic
to your GetProperty call.More info: http://msdn.microsoft.com/en-us/library/zy0d4103(v=vs.110).aspx
Best guess without knowing more about your application, is the following sub-exression results in
null
:At that point, the subsequent
.GetValue()
call will fail with your reported error.The problem is that you don't have properties there in your classes, they are public fields really. A public property looks like
but in your case there is lack of both getters and setters.
Change
GetProperty()
toGetField()
and it will work. Or make your fields properties. Personally, I would go with the second option since it is a better idea to use properties instead of public fields.