Re: Best practice and is there a difference?
- From: Joe Greer <jgreer@xxxxxxxxxxxxxx>
- Date: Tue, 17 Mar 2009 12:40:17 +0000 (UTC)
"Jim H" <jimh@xxxxxxxxxxxxx> wrote in
news:#O9C#ujpJHA.996@xxxxxxxxxxxxxxxxxxxx:
When creating member objects in a C# class what's the difference
between initializing the member where it's defined and using a
constructor. Is there a best practice for this. I come from a C/C++
background and like constructors, but I don't know if there is a
performance and/or readability preference in C#. This is for basic
classes and not classes where the constructor takes arguments.
example:
public class A
{
private String string1;
private int number1;
private List<String> bigList;
public A()
{
string1 = String.Empty;
number1 = 16;
bigList = new List<String>();
}
}
or
public class A
{
private String string1 = String.Empty;
private int number1 = 16;
private List<String> bigList = new List<String>();
}
Side question: Do the new preoperty defs with anonymous members need
to be initialized manually or in the constructor, or does it happen
automatically?
example:
public class A
{
public String FileName { get; set; }
}
Here is my take on it, fwiw. Barring special needs (always have to have
the disclaimer...), If a members value doesn't depend upon parameters
passed to the constructor, I go ahead and initialize them where it is
defined. Since all objects in C++ have to be new-ed to exist, this
works out to be similar to the default constructor in C++. For members
which take on values based upon parameters, I initialize them in the
constructor. So, I might have...
public class A
{
private List<string> myStrings = new List<string>();
private ExternalState myExternalState;
A(ExternalState externalState)
{
myExternalState = externalState;
myStrings.Add("one");
}
}
In the above case, while I create the list at the member declaration, I
still have to add elements to it in the constructor (just as you would
in C++).
So, in short, I use member declaration initialization to take the place
of default construction and otherwise put things into the constructor.
joe
.
- References:
- Best practice and is there a difference?
- From: Jim H
- Best practice and is there a difference?
- Prev by Date: Re: No application is associated with the specified file for this operation
- Next by Date: Re: Usage of double.epsilon
- Previous by thread: Re: Best practice and is there a difference?
- Next by thread: Send Newsletter in C#
- Index(es):
Relevant Pages
|