locked
Object reference not set to an instance of an object. in C# RRS feed

  • Question

  • User496087241 posted

    How can I create an instance and refer to its child objects?  Below class item has multiple child classes.  I am getting Object reference not set to an instance of an object.  Can I create the parent class without creating the child classes?  From below snippet, I instantiate the parent class hoping the child classes can be referred from its parent.  It appears I have to instantiate every child class.  Shouldn't instantiate Item item = new Item(); be sufficient?  What is the best way to instance and refer to the parent item class after populating data to each child class?  How do I populate date into each field?

     Warehouse.cs contains class information:

    namespace Warehouse
    {

    public class Item
    {
    public Location location { get; set; }
    }

    public class Location
    {
    public ProductLocation productLocation { get; set; }
    public string condition { get; set; }
    public PackageWeightandSize packageweightandsize { get; set; }
    public Product product { get; set; }
    public string sku { get; set; }
    public string groupIds { get; set; }
    }

    public class ProductLocation
    {
    public int quantity { get; set; }
    }

    public class PackageWeightandSize
    {
    public Dimensions dimensions { get; set; }
    public string packageType { get; set; }
    public Weight weight { get; set; }
    }

    public class Dimensions
    {
    public float height { get; set; }
    public float length { get; set; }
    public string unit { get; set; }
    public float width { get; set; }
    }

    public class Weight
    {
    public string unit { get; set; }
    public float value { get; set; }
    }

    public class Product
    {
    public string brand { get; set; }
    public string size { get; set; }
    public string name { get; set; }
    public string[] upc { get; set; }
    }

    }

    Code snippet getting error:

    Item item = new Item();

    item.location.sku = reader["SKU"].ToString(); <----System.NullReferenceException: 'Object reference not set to an instance of an object.'
    item.location.condition = reader["condition"].ToString();
    item.location.ProductLocation.quantity = Int32.Parse(reader["Quantity"].ToString());

     

    Wednesday, April 11, 2018 4:34 AM

Answers

  • User475983607 posted

    What is the best way to instance and refer to the parent item class after populating data to each child class?

    There several ways to initialize an object in C#.

    A constructors.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

    public class Item
    {
    public Location location { get; set; }

    public Item()
    {
    location = new Location();
    }
    }

    public class Location { public ProductLocation productLocation { get; set; } public string condition { get; set; } public PackageWeightandSize packageweightandsize { get; set; } public Product product { get; set; } public string sku { get; set; } public string groupIds { get; set; } public Location() { productLocation = new ProductLocation(); packageweightandsize = new PackageWeightandSize(); product = new Product(); } }

    How do I populate date into each field?

    Using an Object Initializer

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer

    Item item = new Item()
                {
                    location = new Location()
                    {
                        condition = "condition",
                        groupIds = "groupIds",
                        packageweightandsize = new PackageWeightandSize()
                        {
                            dimensions = new Dimensions()
                            {
                                height = 1,
                                length = 1,
                                unit = "unit",
                                width = 1
                            },
                            packageType = "packageType",
                            weight = new Weight()
                            {
                                unit = "unit",
                                value = 1
                            }
                        },
                        product = new Product()
                        {
                            brand = "brand",
                            name = "name",
                            size = "size",
                            upc = new string[] { "upc" }
                        },
                        productLocation = new ProductLocation()
                        {
                            quantity = 1
                        },
                        sku = "sku"
                    }
                };

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 11, 2018 10:57 AM
  • User465171450 posted

    Creating an item doesn't initialize a location. You have to initialize it. Otherwise attempting to access location.anything will fail since location isn't anything. You can initialize it in a default constructor like so:

    public class Item
    {
         public Item()
         {
              location = new Location();
         }
    public Location location { get; set; }
    }

    One of the first rules in development is to make sure everything is properly initialized. Never attempt to access something you don't know if it exists, so always initialize.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 12, 2018 11:27 AM

All replies

  • User1120430333 posted

    It appears I have to instantiate every child class.

    Yes that is correct.

    Shouldn't instantiate Item item = new Item(); be sufficient?

    No that is not correct.

    You would have to execute code against the parent to instance each child in the parent after the parent is instanced.

    Parent parent = new Parent();

    parent.child = new child();

    Or you could do this within the parent so when the parent is instanced the child is instanced too within the parent.

    Because the private backing variable for the child public property is being instanced within the parent, the child is instanced too when the parent is instanced.  I leaned the technique long ago from a C# certification testing book. :)

    public class Parent
    {
    
       private Child thechild = new Child(); 
    
       public Child SomeChild
       {
            get
            {
                return thechild;
            }
            set
            {
                thechild = value;
            }
        }
    }
    

    Wednesday, April 11, 2018 6:37 AM
  • User475983607 posted

    What is the best way to instance and refer to the parent item class after populating data to each child class?

    There several ways to initialize an object in C#.

    A constructors.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors

    public class Item
    {
    public Location location { get; set; }

    public Item()
    {
    location = new Location();
    }
    }

    public class Location { public ProductLocation productLocation { get; set; } public string condition { get; set; } public PackageWeightandSize packageweightandsize { get; set; } public Product product { get; set; } public string sku { get; set; } public string groupIds { get; set; } public Location() { productLocation = new ProductLocation(); packageweightandsize = new PackageWeightandSize(); product = new Product(); } }

    How do I populate date into each field?

    Using an Object Initializer

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer

    Item item = new Item()
                {
                    location = new Location()
                    {
                        condition = "condition",
                        groupIds = "groupIds",
                        packageweightandsize = new PackageWeightandSize()
                        {
                            dimensions = new Dimensions()
                            {
                                height = 1,
                                length = 1,
                                unit = "unit",
                                width = 1
                            },
                            packageType = "packageType",
                            weight = new Weight()
                            {
                                unit = "unit",
                                value = 1
                            }
                        },
                        product = new Product()
                        {
                            brand = "brand",
                            name = "name",
                            size = "size",
                            upc = new string[] { "upc" }
                        },
                        productLocation = new ProductLocation()
                        {
                            quantity = 1
                        },
                        sku = "sku"
                    }
                };

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 11, 2018 10:57 AM
  • User496087241 posted

    Hi,

    Thank you very much to help me better understanding how to create constructors.  As a learner with VB background , it would be harder to understand classes.  

    It seems like you created the constructor in the Location child class then instantiate the subchild classes (ProductLocation, PackageWeightandSize, Product) within. 

    I will need to the same to add a constructor in Packageweightandsize child class below to refer dimensions and weight.

    public Packageweightandsize()
    {

    dimensions = new Dimensions();
    weight = new Weight();
    }

    My question is:  Can we create a constructor within Dimensions, Weight, and Product classes instead of creating them from its parent class? I am thinking whether I can create a constructor in Dimensions and Weight class.  Lastly, are these child classes consider inheritance since the child class is referring to the subchild classes.  

    Any explanation would be appreciated and could help me better understanding classes.

    Thanks again. 

    Wednesday, April 11, 2018 11:51 PM
  • User496087241 posted

    Hi DA924,

    From your example above, I am getting compile error in VS on line parent.child = new child();  The error is: "parent is a available but it is used like a type".  Please advise.

    Wednesday, April 11, 2018 11:54 PM
  • User1120430333 posted
    //first way
    
    public class Parent
    {
       public string FirstName {get; set;}
       piblic string LastName {get; set;]
    
       public Child child;
    
    }
    
    ---------------------------------
    //second way.. public class Parent { public string FirstName {get; set;} public string LastName {get; set;] public Child child {get; set;} } ------------------------------------ public class Child { public string Address {get; set;} } ---------------------------------------------- Some code....... Parent parent = new Parent(); parent.child = new Child(); parent.child.Address = "999 SomeStreet";

    Thursday, April 12, 2018 1:21 AM
  • User36583972 posted

    Hi Brian,

    DA924 and mgebhard have given you an reasonable explanation on your issue. You can try a several way to initial a parent class which will create subclass instances together.

    Brian_Ho@msn.com

    My question is:  Can we create a constructor within Dimensions, Weight, and Product classes instead of creating them from its parent class? I am thinking whether I can create a constructor in Dimensions and Weight class.  Lastly, are these child classes consider inheritance since the child class is referring to the subchild classes.  

    No, if you want to use multiple child classes instance in your parent class, you need to create the child classes instance(or assignment values). If you only define a child class without call the corresponding constructor(or without assignment values), you will also get the 'System.NullReferenceException: 'Object reference not set to an instance of an object.'' error.

    Constructors enable the programmer to set default values, limit instantiation, and write code that is flexible and easy to read, in another word, it will initial some settings before initializing the class(parent class). Then, you can directly access these initial settings after instantiation.

    For more detailed about Constructors, please see Constructors (C# Programming Guide)

    Best Regards,

    Yong Lu

    Thursday, April 12, 2018 3:04 AM
  • User465171450 posted

    Creating an item doesn't initialize a location. You have to initialize it. Otherwise attempting to access location.anything will fail since location isn't anything. You can initialize it in a default constructor like so:

    public class Item
    {
         public Item()
         {
              location = new Location();
         }
    public Location location { get; set; }
    }

    One of the first rules in development is to make sure everything is properly initialized. Never attempt to access something you don't know if it exists, so always initialize.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, April 12, 2018 11:27 AM