473,320 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Initialising variables inside or outside contructor

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?
Currently, everything in my constructor could be just inside the class
definition, rather than it all be split into the two chunks. Are there
things I can only do in the constructor, any advantages to either?

--
Daisy The Cow
Now playing: Daniel Bedingfield - Gotta Get Through This
Nov 13 '05 #1
9 6113
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?Currently, everything in my constructor could be just inside the classdefinition, rather than it all be split into the two chunks. Are therethings I can only do in the constructor, any advantages

to either?
Well the "ReadOnly variable" must be initialized in
the constructor; out of constuctor they are "constants".
Hector...

"The best way to predict the future, is to invent it"
Nov 13 '05 #2
Hello Daisy,

Aside from early vs. late binding, not really. Class constructors are more
or less safeguards against uninitialized variables being used by the
consumer of the class. When you call a parameterized constructor and it
initializes it's variables and properties, then you are ensuring that the
variable is populated before first use by the consumer. It still follows the
normal steps in the class lifetime process.
So,

public class MyClass : UserControl
{
public int iRowHeight = 20;
public MyClass()
{

}
}

could be done the same way:
public class MyClass : UserControl
{
public int iRowHeight;
public MyClass(int RowHeight)
{
iRowHeight = RowHeight;
}
}

HTH,

Bill P.
"Daisy" <da***@nospam.oops> wrote in message
news:be**********@linux01.dannytuppeny.com...
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?
Currently, everything in my constructor could be just inside the class
definition, rather than it all be split into the two chunks. Are there
things I can only do in the constructor, any advantages to either?

--
Daisy The Cow
Now playing: Daniel Bedingfield - Gotta Get Through This

Nov 13 '05 #3
"Hector Martinez" <hm********@uci.cu> wrote in message
news:0c****************************@phx.gbl...
Well the "ReadOnly variable" must be initialized in
the constructor; out of constuctor they are "constants".


I also realised adding controls, setting properties of objects etc., can
only be done in the constructor :)
--
Daisy The Cow
Now playing: Flip & Fill - I Wanna Dance With Somebody [Flip & Fill Mix]
Nov 13 '05 #4
Hector Martinez <hm********@uci.cu> wrote:
Well the "ReadOnly variable" must be initialized in
the constructor; out of constuctor they are "constants".


No, readonly variables can be initialised in variable initializers.
There's no difference between:

public class Test
{
readonly int x = 20;
}

and

public class Test
{
readonly int x;

public Test()
{
x=20;
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #5
-----Original Message-----
Hector Martinez <hm********@uci.cu> wrote:
Well the "ReadOnly variable" must be initialized in the constructor; out of constuctor they
are "constants".
No, readonly variables can be initialised in variable initializers.There's no difference between:

public class Test
{
readonly int x = 20;
}

and

public class Test
{
readonly int x;

public Test()
{
x=20;
}
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
.

I have to try but I think you can't do something like
this...because out of constructor the readonly variable
become a constant

"...Direct assignments to readonly fields can only
occur as part of that declaration or in an instance
constructor or static constructor in the same class..."

C# Language Specification by ECMA
Nov 13 '05 #6
"Jeff Louie" <an*******@devdex.com> wrote in message
news:O$**************@TK2MSFTNGP11.phx.gbl...
Daisy... If you initialize at the time of declaration you will minimize
init errors, especially with multiple constructors. Use the
constructor for dynamic initialization.


That's what I've been doing. My constructor only has things that I didn't
think would work outside it, like Controls.Add(), setting properties on
objects declared outside the constructor, etc.
--
Daisy The Cow
Now playing: R Kelly - Ignition [Remix]
Nov 13 '05 #7
Hector Martinez <hm********@uci.cu> wrote:
I have to try but I think you can't do something like
this...because out of constructor the readonly variable
become a constant

"...Direct assignments to readonly fields can only
occur as part of that declaration or in an instance
constructor or static constructor in the same class..."

C# Language Specification by ECMA


Note the "as part of that declaration" bit. Furthermore, try it - it
works.

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

"...Direct assignments to readonly fields can only
occur as part of that declaration or in an instance
constructor or static constructor in the same class..."

C# Language Specification by ECMA
Note the "as part of that declaration" bit. Furthermore,

try it - itworks.


"as part of that declaration" means:
readonly int i = 5;
In the other hand take a look to this...

public class GameGrid
{
public bool[,] Grid;

internal readonly int Rigth;
internal readonly int Down;

public GameGrid(int r, int d)
{
Rigth = r; Down = d;
Init();

for (int i= 0; i< Rigth; i++)
for (int j= 0; j< Down; j++)
Grid[i,j] = false;
}

private void Init()
{
Grid = new bool[Rigth,Down]; //Important Line
}
}
I can put the "Important line" inside the constructor,
because i receive a message which tell me that the
expresion need constant (or somethin like that), but in
the way i show up its work. Why?

"Because out of constructor "Rigth" and "Down" readonly
field become in constants.

Don't take in the bad way, ok.
Nov 13 '05 #9


I'm sorry, you are rigth, i just missunderstand what
you post...

is exactly like this :

You can't do this:

public class test
{
public readonly int y = 25;
}

or this:

public class test
{
public readonly int y;

public test
{
y = 25;
}
}
What you post is exactly what I want to post, I only
don't read ok what you post. I hope you understand me...

I'm sorry , again.
Nov 13 '05 #10

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

Similar topics

3
by: J. Campbell | last post by:
In the following example, is there any way to directly access the "outside" variable, j, from the "inside" scope (after the inside j has been created)? Thanks, Joe #include<iostream> ...
7
by: Michael | last post by:
Hi newsgroup, as the subject indicates I am looking for an advice using global variables. I am not if this problem is more about style then C. If its wrong in thi group, sorry. So I have a...
4
by: Bryan Green | last post by:
So I'm working on a project for a C# class I'm taking, where I need to keep some running totals via static variables. I need three classes for three different types of objects. The base class and...
2
by: Rob Meade | last post by:
Hi all, New to .Net - still finding my feet...quick question... In one of my functions I have about a dozen variables being declared at the top - the first thing within the function, about 2...
107
by: DaveC | last post by:
I always used to initialise variables at declaration, then a couple of colleagues started telling me it was bad practice and that the compiler should be left to spot the use of uninitilised...
10
by: pod | last post by:
Hello Using ANSI C... The following code is causing a bit of bother.... UINT16 x, y, z = 0 Would people expect x and y and z to be set to 0 ?
9
by: Jim | last post by:
Hi, I want to declare that that a valarray of a certain name exist at the beginning of some code, but I can't instatiate it until I've read in some parameters later on in a for loop i.e. int...
1
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have...
26
by: optimistx | last post by:
A variable in global scope var a1 = 'contents of global variable a1'; can be references (with some limitations) as window; // or window.a1; // or even window;
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.