C# : I am trying to create collection class with list of some other user defined class but it show object not set to be an instance of an object when i trying to add object in main object.
Here is my C# code :
namespace ConsoleApplication2
{
public class Monthlst
{
public List<Monday> Monday { get; set; }
public List<Tuesday> Tuesday { get; set; }
public List<Wednesday> Wednesday { get; set; }
public List<Thursday> Thursday { get; set; }
public List<Friday> Friday { get; set; }
public List<Saturday> Saturday { get; set; }
public List<Sunday> Sunday { get; set; }
}
public class Monday
{
public int days { get; set; }
}
public class Tuesday
{
public int days { get; set; }
}
public class Wednesday
{
public int days { get; set; }
}
public class Thursday
{
public int days { get; set; }
}
public class Friday
{
public int days { get; set; }
}
public class Saturday
{
public int days { get; set; }
}
public class Sunday
{
public int days { get; set; }
}
class Program
{
static void Main(string[] args)
{
Monthlst objmonth = new Monthlst();
Wednesday wednes = new Wednesday();
wednes.days = 5;
objmonth.Wednesday.Add(wednes); // here i am getting error object not set to....
}
}
}
Here i am just create instance of my Monthlst class in main method and the object of wednesday class in list property of Monthlst object but why it show me error i dont know Is there any wrong thing i am doing or not please explain….
Thanks,
Raj
Yes, you’re not initializing your properties. After construction, all of the
Monthlstproperties will benull. You need to create a list before adding to it. For example:Alternatively, make the constructor for
Monthlstinitialize all its properties.Aside from that, I think the design is somewhat ropy in various ways, but that’s a different matter.