Home > database >  C# property for fields with user-defined class type
C# property for fields with user-defined class type

Time:10-08

First, define a class named AAA:

class AAA
{
    public int a = 1;
}

Then, define another class BBB contains a field with type AAA (a property A for that field, and the field has been initialized, namely, not null):

class BBB
{
    private AAA a = new AAA();

    public AAA A { set; get; }
    
    public bool isNull()
    {
        return a == null;
    }
}

Next, I wrote the code below outside:

BBB b = new BBB();
var flag = b.isNull();  // the value is FALSE
b.A.a = 3;              // NullPointerException

As is stated in the comment above, b.isNull() returns FALSE. So, the field a is not null. However, the 3rd line (b.A.a = 3) throws a NullPointerException.

If property A can get the pointer (C# has no pointer, I mean the address references to the real object a) of the field a, this exception should not be thrown.

My question is whether it would be possible to get an object using property in C#.

CodePudding user response:

Because you have initialized a not A. b.A is null.

But I am not sure that what are you trying to achieve by declaring a and A with the same type.

I don't think you need to declare A in your case.

CodePudding user response:

Here you go as per my comment here is the fix. Keeping in mind your question is not clear so this is what I assume you want. class BBB {

public BBB()
{
A = new AAA();
}
public AAA A { set; get; }
public bool isNull()
{
   return A == null;} //will always return false
}
  •  Tags:  
  • c#
  • Related