-1
public class s
{
    public string s1 { get; set; }
}

public class s2
{
    public s s3 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        s2 objs2 = new s2();
        objs2.s3.s1 = "asdf";
    }
}

getting runtime error because objs2.s3 is null. i want to know how to achieve this.

Please also let me know why this is happening so if you got some time. thanks.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
chanti
  • 95
  • 1
  • 9

4 Answers4

3

You never actually initialize s3 anywhere. If you always want it to default to a new instance of s, you can create a constructor:

public class s2
{
    public s2()
    {
        s3 = new s();
    }
}

s2 objs2 = new s2();

Or, if you don't want to modify s2, you can simply initialize the value when you instantiate the object:

s2 objs2 = new s2 { s3 = new s() };
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

The class s is nullable and therefore the s3 property is null by default. You need to instantiate it before use.

One way would be to have the constructor of the class s2 create an instance for you.

It would then become:

public class s2
{
    public s s3 { get; set; }
    public s2()
    {
      s3 = new s();
    }
}
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
1

In order for your code to work, you need to initialize s3 property of s2 instance with the new operator because it is a reference type (check reference vs value types here).

This is the line that you are missing:

s2.s3 = new s();

And here is the complete code that will run correctly:

public class s
{
    public string s1 { get; set; }
}

public class s2
{
    public s s3 { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        s2 objs2 = new s2();
        s2.s3 = new s();
        objs2.s3.s1 = "asdf";
    }
}
Bishoy
  • 3,915
  • 29
  • 37
1

additionally to the other answer you can inisialise s3 in Main().

s2 objs2 = new s2()
{
    s3 = new s()
};