Anonymous
Anonymous

Reputation: 1979

C# Defined type of class variable

I'm not even sure if the title of this question is correct, but I wasn't sure how to describe the problem. Basically I have two following classes:

class A
{
    public B b { get; set; }
}

class B
{
    public string name { get; set;}
}

After I create an object of my A class, I'm trying to define class B variable name like so:

A classA = new A();
A.B.name = "TEST";

However, I keep getting the follow error:

Object reference not set to an instance of an object.

Obviously, I'm doing something completely wrong. Any help would be appreciated.

Thanks!

Upvotes: 1

Views: 122

Answers (5)

burning_LEGION
burning_LEGION

Reputation: 13460

Initialize class B

A classA = new A();
classA.b = new B();
classA.b.name = "TEST";

Upvotes: 0

Jim
Jim

Reputation: 6881

You need an instance of your class B.

A classAInstance = new A();
classAInstance.b = new B();
classAInstance.b.name = "TEST";

Upvotes: 0

User1000547
User1000547

Reputation: 4311

B is null. You need to instantiate B before you can reference it.

A classA = new A();
classA.B = new B();
classA.B.name = "TEST";

Upvotes: 0

rsbarro
rsbarro

Reputation: 27359

You'll need to call it like this:

A classA = new A();
classA.b = new B();
classA.b.name = "TEST";

The issue is that you need to instantiate the b property on classA instance you created.

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27614

You haven't created instance of B so it is null (that is inside your instance of A). You can e.g. instantiate it inside constructor:

class A
{
    public B b { get; set; }

    public A()
    {
        b = new B();
    }
}

Upvotes: 10

Related Questions