1

I have a complex c# class which has several flat members and several nested complex types.

As a general practice, I don't initialized "Nested" complex types if don't have data for them.

For example, if I have a class

Public class Person
{
 public string FirstName{get;set;}
 public Address{get;set;}
}

I will not do Person p = new Person(){FirstName="Test", Address = new Address()};

However, I'm TOLD to initialize "all sub" complex types even though, in my opinion this should not be case. Why allocate memory when we don't have data. How do you decide if object is empty or not. Do you compare all values/ Define some sort of lag, or defined a specialized sub class to represent empty instance.

Your feedback will be appreciated.

2

3 Answers 3

1

Runtime cost of checking every property for null before access could be higher than initializing all fields with "empty" objects (see Null Object pattern). Memory cost of "empty"/"null object" can be very small as you can simply share single read only instance across all you objects.

Also if you keep some parts of some objects non-initialized you put very high cost on developers to look up if null check is needed before accessing/using your objects.

Basically you may get some benefits for not initializing some fields but you'll need to pay a lot of time making sure all access to properties is properly guarded from accessing null fields.

Sign up to request clarification or add additional context in comments.

Comments

1

To keep simple, you can initialize inside the constructor:

public class Person
{
    public Person()
    {
        this.Address = new Address();
    }
    public string FirstName {get; set;}
    public Address {get; set;}
}

.

// Don´t need to do Person p = new Person(){ FirstName="Test", Address = new Address()}; 
Person p = new Person();

Dont need to worry, unless you have millions of objects, or you know you will have.

Comments

0

You can use this pattern:

Public class Person
{
  private Address address;

  public Address Address 
  {
    get
    {
      return address ?? (address = new Address()); 
    }
  }
}

1 Comment

The problem is that I have some logic based on the the sub type being "null" or "not". For example, if Address is null, I may let user enter it on the screen, else just display it is as read-only. So are we saying that 'initializing' sub types is better? What if user starts calling the method on it. Will not that cause unpredictable behavior? Atleast, if the object is null, I will atleast consistently get "Null Reference exception".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.