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());
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;
}
}
}
If you find the post has answered your issue, then please mark post as 'answered'.
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.
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.
//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";
If you find the post has answered your issue, then please mark post as 'answered'.
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.
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
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.
Don't forget to mark useful responses as Answer if they helped you towards a solution.
Member
6 Points
18 Posts
Object reference not set to an instance of an object. in C#
Apr 11, 2018 04:34 AM|Brian_Ho@msn.com|LINK
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());
Contributor
4863 Points
4121 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 11, 2018 06:37 AM|DA924|LINK
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. :)
All-Star
52101 Points
23237 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 11, 2018 10:57 AM|mgebhard|LINK
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
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
Member
6 Points
18 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 11, 2018 11:51 PM|Brian_Ho@msn.com|LINK
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.
Member
6 Points
18 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 11, 2018 11:54 PM|Brian_Ho@msn.com|LINK
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.
Contributor
4863 Points
4121 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 12, 2018 01:21 AM|DA924|LINK
Star
11454 Points
2439 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 12, 2018 03:04 AM|Yohann Lu|LINK
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.
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
All-Star
26071 Points
5892 Posts
Re: Object reference not set to an instance of an object. in C#
Apr 12, 2018 11:27 AM|markfitzme|LINK
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:
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.