Saturday, November 24, 2018

c# - Trying to use a class as a property for other class

Usually, I only use a simple class to organize my code, but today I've tried to use a class inside another class as a property so it becomes even more organized, but I'm not being able to make it work.


This is the .cs file which contains the classes:


namespace TestZone
{
class Item
{
public Category Category1 { get; set; }
public Category Category2 { get; set; }
}
class Category
{
public string Title { get; set; }
public string Content { get; set; }
}
}

And this is the Program.cs file:


using System;
namespace TestZone
{
class Program
{
static void Main(string[] args)
{
Item myItem = new Item();
myItem.Category1.Title = "My title"; //This line throws an error.
Console.WriteLine(myItem.Category1.Title);
Console.ReadLine();
}
}
}

For some reason, the 10th line of Program.cs, where I try to assign a value to myItem.Category1.Title, this error shows up:



System.NullReferenceException: 'Object reference not set to an
instance of an object.'
TestZone.Item.Category1.get returned null.



I have also tried to put the 'Category' class inside the 'Item' class too and changed it to public like the code below, but still didn't work.


namespace TestZone
{
class Item
{
public Category Category1 { get; set; }
public Category Category2 { get; set; }
public class Category
{
public string Title { get; set; }
public string Content { get; set; }
}
}
}

I'm surely doing something wrong and I would appreciate if you could tell me what it is.

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...