• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

Technical Question

Hi Experts ..

private List<CustomClass> myProperty;

public List<CustomClass> MyProperty
{
     get
     {
               // return ..
      }

     set
     {
            // Which way is better???
            1) myProperty = value;
             or
            2) myProperty.Clear();
                myPropety.AddRant(value);???
           
     }
}
0
DrAske
Asked:
DrAske
  • 3
  • 2
1 Solution
 
JimBrandleyCommented:
You need the first in this case because:
myProperty.Clear();
myPropety.AddRant(value);

Will throw an exception because myProperty is undefined.

Jim
0
 
DrAskeAuthor Commented:
Assume that it is already being initialized in the constructor.
0
 
JimBrandleyCommented:
I had added another response, and when I hit submit, my internet connection was gone. So, here goes again:

I see two issues with your second method.
1. Since the property no longer saves a reference to the one passed in by the caller, that one may be disposed sooner. Might be a problem, and might not.
2. If you make it:
set
{
       if (myProperty == null)
            myProperty = new List<CustomClass>();
       myProperty.Clear();
       myPropety.AddRange(value);
}

Then for a single call, you are creating two instances of the list class (one by the caller, one here) instead of one, and you spend time copying the contents. I think the old style:
      member = value;
is more efficient both in terms of memory and time.

Jim
0
 
DrAskeAuthor Commented:
thank you :o)
0
 
JimBrandleyCommented:
My pleasure. Good luck,

Jim
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now