473,549 Members | 2,346 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

initialising properties in static constructor

I have a class with a dozen+ properties, some of which will be set a
value, and some not, depending on the constructor called. I also have a
method which has only one overload and all of the properties are being
sent to it.

My question is, because some of these properties will not be initialised
by the constructor used, calling this method in some cases will crash my
app unless I initialise all the properties at some point in my class.
Is the static constructor the best place to do this?
Regards,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #1
7 2213
Mike P <mr*@telcoelect ronics.co.uk> wrote:
I have a class with a dozen+ properties, some of which will be set a
value, and some not, depending on the constructor called. I also have a
method which has only one overload and all of the properties are being
sent to it.

My question is, because some of these properties will not be initialised
by the constructor used, calling this method in some cases will crash my
app unless I initialise all the properties at some point in my class.
Is the static constructor the best place to do this?


No, a static constructor can't do this. A static constructor has no
instance to deal with.

I'm not sure what you want to happen when the method is called when the
properties haven't been set. Do you want to use some default values (in
which case initialising the properties to the default values at
construction time would be the right way to go) or do you want an
exception to be thrown (in which case, check the current state and
throw InvalidOperatio nException if the relevant properties haven't all
been set).

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
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!
Nov 16 '05 #3
Hi,
My question is, because some of these properties will not be initialised
by the constructor used, calling this method in some cases will crash my
app unless I initialise all the properties at some point in my class.
Is the static constructor the best place to do this?


Nop, unless those properties are static too, meaning that they belong to the
type and not to a particular instance. if this is not the case you should
initialize them inside the constructor ( if they have some default values )
or otherwise throw an exception if they are used without initialization.

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
Nov 16 '05 #4
Mike P <mr*@telcoelect ronics.co.uk> wrote:
I want to use default values...I just wondered whether I should be
setting them in the static constructor or my other constructors.
Static constructors are used to initialise static variables.
I guess the answer is to set the defaults in the other constructors.


Or in the variable declarations.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #5
Mike,

If the properties are based on simple types, you can just initialise the
corresponding fields inline, eg:

private int _aNumber = 12;
private string _someString = "default text";

Cheers,
Chris.
"Mike P" wrote:
I have a class with a dozen+ properties, some of which will be set a
value, and some not, depending on the constructor called. I also have a
method which has only one overload and all of the properties are being
sent to it.

My question is, because some of these properties will not be initialised
by the constructor used, calling this method in some cases will crash my
app unless I initialise all the properties at some point in my class.
Is the static constructor the best place to do this?
Regards,

Mike
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!

Nov 16 '05 #6
Hi,

I would suggest you that take a look at Jon's article about constructors to
know the use and the particularity of a static constructor.

you could also do this

private int i=4;

it does initialize it and you don;t have to put that code in a constructor.
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"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!

Nov 16 '05 #7
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!

Nov 16 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1848
by: Fred | last post by:
Hi I have a class defined in a library that I'd like to add some extra functionality to. This will involve adding a few member variables and a few related methods. As I understand it I can simply inherit from the existing class and add in my new variables and methods - but what about initialisation? Let's say I add new member variables a...
2
11122
by: Dylan | last post by:
what is the best way of initializing a static std::vector data member with some values? (currently I just push_back some values in the constructor if the size == 0) thanks
9
6120
by: Daisy | last post by:
Another this vs that post. Any real difference in declaring variables with default values, eg. public class MyControl : UserControl { public int RowHeight = 20; } Over just declaring the variable, and setting it to 20 in the Constructor?
6
3835
by: bryanhobson | last post by:
I'm fairly new to c#, and I am just trying to work out how a 'properties' dialog works. Currently in my code, I have an object represented by the class 'Dog'. The dog object has several properties. I have added a new windows form, class 'DogProperties'. I'm attempting to use this to allow the user to edit the properties of an instance of...
8
1918
by: Peter Gummer | last post by:
I want to perform some initialisation when an assembly is first loaded. I know about static constructors, but that's not what I want. A class's static constructor is not called until something uses the class at run time. That may be too late. What I'm actually trying to do is hook up a TraceListener so that calls to Debug.Assert will...
7
1456
by: sherifffruitfly | last post by:
Hi, I'm learning the .net Bloomberg api, and it's main class has all of its stuff static. The help then goes on to say that the class is implemented as a singleton. It's cool I guess to make sure not more than one instance can be made, but with everything in the class static, I don't actually understand why even *one* instance is required....
2
2073
by: Christoph Conrad | last post by:
Hi, given the following test case, with CString from Microsofts MFC: ================================================== file 1: CString arr; ==================================================
2
1558
by: mark4asp | last post by:
Q: Initialising and updating a class with only static members & database dependency I have a class with the following members: public static List<ACISACIS_List; static AssetClass() { // blah } public static ACIS Get_ACIS(string sACISCode) { // blah }
7
1890
by: Fraser Ross | last post by:
template<typename T, typename CounterPolicy = SimpleReferenceCount, typename ObjectPolicy = StandardObjectPolicy> class CountingPtr : private CounterPolicy, private ObjectPolicy { private: // shortcuts: typedef CounterPolicy CP; typedef ObjectPolicy OP; T* object_pointed_to;
0
7546
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7471
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
6071
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5387
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5111
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1962
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1082
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
784
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.