Class declarations

  • Thread starter Thread starter web1110
  • Start date Start date
W

web1110

Is this legit? I thought that class members could not be allocated in the
class declaration. I thought this had to go into the constructor. If this
is OK, what are the associated rules?

class WhatEver
{
private object[] thePair=new object[2];

[STAThread]
static void Main(string[] args)
{
 
Yes, it's legitimate. It's equivalent to putting the initialization in
the constructor. I believe that each initialization expression must be
stand-alone... that is, it can't use "this" to access other,
already-initialized members because the initialization order is not
guaranteed.

That said, I prefer to put everything in the constructor so that it's
all in one place. I find even class declarations like

int sales = 0;

to be annoying, because then I have to look two places (the constructor
and the member declaration) to see what the initial values are.

I know other people who avoid putting initialization code in
constructors and prefer member initializations. It's a style thing.
 
I concur. I always use the constructor. I was suprised to see this and it
made me wonder. Thanx
 
web1110 said:
I concur. I always use the constructor. I was suprised to see this and it
made me wonder. Thanx

I don't concur.

I use both direct assignment and constructors.

The great thing with direct assignment is that you tell a future maintainer
that
- No, this member is not null.

Regards
- Michael S
 
Back
Top