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);???
           
     }
}
LVL 9
DrAskeAsked:
Who is Participating?
 
JimBrandleyConnect With a Mentor Commented:
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
 
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
 
DrAskeAuthor Commented:
thank you :o)
0
 
JimBrandleyCommented:
My pleasure. Good luck,

Jim
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.