Hi Mike,
When static constructor is static it cannot initialize instance variables
simply because it has no relations to any instances. Thus you cannot use it
for this purpose unless the fields are not static as well.
You have options:
1. To intialize them in the constructor. If you have more then one
constructor, though, it might be hard to maintain such a code. In this case
initialize them at the moment of their decalration
class Foo
{
Bar b = new Bar()
public Foo(...)
{
}
}
The code for such initialization will be populated by the compiler at the
begining of all constructrs your calass may have. The drawback that some of
the variables will be initialized twise, which depending on the type of the
obejct might be no acceptable. The other limitation is that you cannot use
*this* which in the constructor is allowed.
2. You can initialize the backup fileds of the properties on demand. The
first time the propety is read if the value is not initialized then you
initialize it. This however works for reference types, but not for value
types unless you don't keep some flags and stuff.
public Foo MyProp
{
get
{
if(this.myProp == null)
{
this.myProp = new Foo();
}
return myProp;
}
}
3. you can throw an exception of the roperty is not initialized. Again it
worgs well for reference types, but not for value types unless you don have
special flags
--
HTH
Stoitcho Goutsev (100) [C# MVP]
"Mike P" <mr*@telcoelect ronics.co.uk> wrote in message
news:en******** ******@TK2MSFTN GP12.phx.gbl...
I want to use default values...I just wondered whether I should be
setting them in the static constructor or my other constructors. I
guess the answer is to set the defaults in the other constructors.
Thanks,
Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!