How to get object property from a collection

-2

In order to eliminate the need to write a really long Switch Statement, I want to get the object property from a collection that contains data.

Here is my code:

public class NCAABArchive 
{
    private int id;
    public int HScore;
    public string Road;
    public int RScore;
    public double Line;
    public double LineAvg;
    public double LineSag;
    public double LineSage;
    public double LineSagp;
    public double LineSggm;
    public double LineMoore;


}


        string forecastStr = "coll.LineFox";
        string actualStr = "coll.ActualSpread";

        foreach (NCAABArchive coll in Form1.gui.NCAABArchiveCollection)
        {
            recCtr++;

//System.NullReferenceException // HResult=0x80004003 // Message=Object reference not set to an instance of an object. // Source=BBallStatsPredictions

            //PropertyInfo pinfo = typeof(NCAABArchive).GetProperty(forecastStr);
            //object value = pinfo.GetValue(coll);

            if (recCtr % 100 == 0)
            {
                if (coll.GameScore != null)
                {
                    switch (forecastStr)
                    {
                        case "coll.LineAvg":
                            altargetforecast.Add(coll.LineAvg);
                            break;

                        case "coll.LineSag":
                            altargetforecast.Add(coll.LineSag);
                            break;

                        case "coll.LineSggm":
                            altargetforecast.Add(coll.LineSggm);
                            break;

                        case "coll.LineFox":
                            altargetforecast.Add(coll.LineFox);
                            break;

                        default:
                            break;
                    }

                    //altargetforecast.Add(coll.LineAvg);
                    //alactual.Add(coll.ActualSpread);

                    // altargetforecast.Add(forecastStr);
                    alactual.Add(coll.ActualSpread);
                }
            }

I'm getting an Error Message=Object reference not set to an instance of an object.

How do I instantiate the object, the collection already is instantiated? What am I doing wrong?

c#
object
asked on Stack Overflow Jan 27, 2021 by Trey Balut

1 Answer

0

Your forecastStr is not the property name. It is "coll.{propertyname}".

The problem is that your line:

PropertyInfo pinfo = typeof(NCAABArchive).GetProperty(forecastStr);

is not getting a property because there's not a property called "coll.Linefox".

So pinfo is null and returning the error when you try to access it.

string propName = "LineAvg"
PropertyInfo pinfo = typeof(NCAABArchive).GetProperty(propName);
object value = pinfo.GetValue(coll)

// "value" will be set to coll.LineAvg
answered on Stack Overflow Jan 27, 2021 by Neil W

User contributions licensed under CC BY-SA 3.0