0

I am looking for some advice/suggestions on how best to implement some properties in my class. Consider the following 2 classes:

public class ClassA
{
    // some contents for the class
}

// The following class contains an object of ClassA that
// may or may not be instantiated at all during the lifetime of ClassB
public class ClassB
{
    private ClassA m_classa = null;

    // Then I have a whole bunch of properties that return a value
    // which is either a property of ClassA, if instantiated, or a default value
    // For e.g.
    public string PropertyOne
    {
        get
        {
            return m_classa != null ? m_classa.PropertyOne : string.Empty;
        }
    }

    // The above pattern repeats for all of the properties that I have in ClassB
}

With this approach, I have to do the null check, and specify the default value for every property that I need to implement. It seems like there maybe a better way to do this, especially if I have a lot of properties.

My question is: is this the best way to do this? If not, what are some other approaches that I can take to minimize the amount of code I have to write, and improve readability?

Thanks!

Snooks
  • 91
  • 1
  • 11

1 Answers1

0

You could simplify the get accessor to be

return m_classa?.PropertyOne ?? String.Empty;

It is only syntactic sugar which might improve readability, the generated IL is (practically) the same.

Concerning the class design, I would do a lazy initialization, and include the defaults in the inner class all with appropriate access modifiers, then expose the whole object instead of rewriting individual props.

Cee McSharpface
  • 8,493
  • 3
  • 36
  • 77
  • Thanks! I should've said that I am not on C# 6.0 yet, and I am unable to start using it just yet for various reasons. Any sugar coating I can use for earlier versions? – Snooks Feb 08 '17 at 23:44
  • @Snooks: see the marked duplicate for pre-6.0 options, as well as the current 6.0 option described above. – Peter Duniho Feb 08 '17 at 23:56