Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance of an object. C# GetProperty()

Tags:

c#

reflection

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

like image 818
mmilan Avatar asked Dec 03 '13 20:12

mmilan


1 Answers

The problem is that you don't have properties there in your classes, they are public fields really. A public property looks like

public string PropertyName { get; set; }

but in your case there is lack of both getters and setters.

Change GetProperty() to GetField() 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.

like image 111
Ondrej Janacek Avatar answered Oct 07 '22 05:10

Ondrej Janacek