-1

I have a class that has a objects.I want to set the value for that inner objects.

Question I want to set the value and print name of class Case My code -

public class Case
{
    public string name { get; set; }
}
public class Myclass
{
    public Case C { get; set; }
}
class Hello
{
    static void Main()
    {
        Myclass obj = new Myclass();
        string val = obj.C.name = "Testing";
        Console.WriteLine(val);
        Console.ReadLine();
    }
}

Problem-I am getting null exception.

Any suggestion?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • obj.C is never set to a value during construction After "creating obj", you have to "create C" aswell on this obj with obj.C = new Case(); – Tobi Becht Oct 23 '17 at 14:55

3 Answers3

1

You need to create a new instance of Case first:

obj.C = new Case() ;
string value = obj.C.name = "Testing";
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
0

You need to instantiate C when you create an instance of MyClass. Something like

public class Case
{
    public string name { get; set; }
}
public class Myclass
{
    public Myclass(string name) { C = new Case(); C.name = name; }
    public Case C { get; set; }
}
class Hello
{
    static void Main()
    {
        Myclass obj = new Myclass("Testing");
        string val = obj.C.name;
        Console.WriteLine(val);
        Console.ReadLine();
    }
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
spodger
  • 1,668
  • 1
  • 12
  • 16
0

As obj.C is a complex property You need to instantiate obj.C as well like below,

Myclass obj = new Myclass();
obj.C = new Case();
string val = obj.C.name = "Testing";
Console.WriteLine(val);
Console.ReadLine();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Vijayanath Viswanathan
  • 8,027
  • 3
  • 25
  • 43