Sunday 29 October 2017

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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...