Sunday, September 15, 2019

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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...