static props

  • Thread starter Thread starter boxim
  • Start date Start date
B

boxim

got some static props in some classes
some of the props need to refer to other static members of the other classes
however, cos they're not simple types, cant use const, have to use readonly
how do i ensure that they're initialised in a particular order
e.g.
class one { public static readonly MyType Val1 = new MyType("hmmm"); }
class two { public static readonly MyType Val2 = new
MyType(one.Val1.GetTheString); }
two is reliant on one.Val1 being initialised
any ideas?


tia

sam martin
 
boxim said:
got some static props in some classes
some of the props need to refer to other static members of the other classes
however, cos they're not simple types, cant use const, have to use readonly
how do i ensure that they're initialised in a particular order
e.g.
class one { public static readonly MyType Val1 = new MyType("hmmm"); }
class two { public static readonly MyType Val2 = new
MyType(one.Val1.GetTheString); }
two is reliant on one.Val1 being initialised
any ideas?

Unless there are circular dependencies, it should all be fine. When the
type initializer for class two is automatically invoked, it will
automatically invoke the type initializer for class one.

When there are circular dependencies things get harder, because you
can't force one initializer to finish before the other one does, if you
see what I mean.
 
boxim,

I would initialize all of the properties to null when you declare them.
Then, create a static constructor where you set the properties. Readonly
properties can be set in the constructor (for instances) or static
constructor (for types). This will allow you to control the order of
initialization.

Hope this helps.
 
Nicholas Paldino said:
I would initialize all of the properties to null when you declare them.
Then, create a static constructor where you set the properties. Readonly
properties can be set in the constructor (for instances) or static
constructor (for types). This will allow you to control the order of
initialization.

But there's no problem here anyway - class two requires class one to be
initialized, so it will be.

The problem is more likely to occur when the order of initialization
*within* a class is important - and there, the initializers run in the
textual order of declaration. For robustness, it would be a good idea
to put the code in a static constructor, however.
 
Back
Top