473,509 Members | 2,880 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Should I explicitly initialize all member variables?

I come from a background of Ada and C++ programming, where it was considered
good practice to explicitly initialize every variable.

Now that I'm programming in C# I think that it would be best NOT to
initialize class members, because every type has well defined initialization
anyway.

eg.

class C
{

int i = 0; // redundant

int j; // better?

MyClass m = null; // redundant

MyClass m; // better?
}

What's the best practice?

TIA,

Javaman
Nov 17 '05 #1
30 6761
Javaman59,

The best thing to do is to initialize every variable.
Then, there's always a default value for every variable.
It should probably make your code 'neater' and easier to decipher, it
makes thing clear.

Sorry if this isn't what you like but,

Seen Sharp

Nov 17 '05 #2
I must STRONGLY disagree. You should not initialize every variable to
its default value as that adds extra overhead. The variable
initialization is moved to the default constructor if you initialize it
by declaring it like this:

class myclass
{
int i = 0;
}

c# for above would generate a constructor and inside you would see
this.i = 0;

assignment.

Waste of cycles man.
Visually Seen # wrote:
Javaman59,

The best thing to do is to initialize every variable.
Then, there's always a default value for every variable.
It should probably make your code 'neater' and easier to decipher, it
makes thing clear.

Sorry if this isn't what you like but,

Seen Sharp

Nov 17 '05 #3
I would say not to initialize them as it adds extra code to the underlying
MSIL which in the end takes longer to execute.
Brian Delahunty
Ireland

http://briandela.com/blog
"Javaman59" wrote:
I come from a background of Ada and C++ programming, where it was considered
good practice to explicitly initialize every variable.

Now that I'm programming in C# I think that it would be best NOT to
initialize class members, because every type has well defined initialization
anyway.

eg.

class C
{

int i = 0; // redundant

int j; // better?

MyClass m = null; // redundant

MyClass m; // better?
}

What's the best practice?

TIA,

Javaman

Nov 17 '05 #4
Javamman.. The following two lines of code are NOT equivalent in C#.
MyClass m = null; // redundant

MyClass m; // better?<

The second line simply creates an unitialized variable. It does not
default to null.

http://www.geocities.com/Jeff_Louie/OOP/oop5.htm

Regards,
Jeff
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #5
Jeff Louie <je********@yahoo.com> wrote:
Javamman.. The following two lines of code are NOT equivalent in C#.
MyClass m = null; // redundant MyClass m; // better?<

The second line simply creates an unitialized variable. It does not
default to null.


Yes it does - if it's a member variable. If it's a *local* variable it
remains uninitialised, but the subject line makes it clear that the
question is about member variables. From the spec, section 12.2 (ECMA
numbering):

<quote>
The following categories of variables are automatically initialized to
their default values:

* Static variables.
* Instance variables of class instances.
* Array elements.

The default value of a variable depends on the type of the variable and
is determined as follows:

* For a variable of a value-type, the default value is the same as
the value computed by the value-type's default constructor (11.1.1).
* For a variable of a reference-type, the default value is null.
</quote>
http://www.geocities.com/Jeff_Louie/OOP/oop5.htm


There are a couple of slight errors in that, in the Java bit:

4) Value types *don't* actually derive from anything - only the
reference type which is used for boxing the value type derives
(indirectly) from Object. It's all a bit odd, but is spelled out in the
CLI spec.

9) Java has enums now too - they're very different to C# ones though
(and far superior, IMO).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #6
>Yes it does - if it's a member variable.<

Well I'll be. I will fix that.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #7

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Mike Schilling <ms*************@hotmail.com> wrote:
"Brian Delahunty" <Br************@discussions.microsoft.com> wrote in
message news:19**********************************@microsof t.com...
>I would say not to initialize them as it adds extra code to the
>underlying
> MSIL which in the end takes longer to execute.


Does the JIT generate any code when a field is initialized to its default
value? (Real question, not rhetorical; I have no idea.)


Yes, it seems to. Here's a quick pair of test programs:

using System;

public class TestWithInit
{
int a0=0, a1=0, a2=0, a3=0, a4=0, a5=0, a6=0, a7=0, a8=0, a9=0;
int b0=0, b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0, b8=0, b9=0;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

and:

using System;

public class TestNoInit
{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestNoInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

On both .NET 2.0 beta 2 and .NET 1.1, the version without explicit
initialisation is faster than the version with initialisation - with or
without optimisation turned on. The difference is actually reasonably
significant - but only in a test where nothing other than object
creation (and GC, obviously) occurs.

I would personally be very reluctant to change any coding habits based
on that though.


Me too (even if my habit weren't to leave such initializations off.)

But I find your results odd; it's a simple enough JIT optimization to make.
Nov 17 '05 #8
No it's not. The JIT would have to compare each value of the initializer
with the default value, this would take much more time than a simple
assignment.

Willy.

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:OM**************@tk2msftngp13.phx.gbl...

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Mike Schilling <ms*************@hotmail.com> wrote:
"Brian Delahunty" <Br************@discussions.microsoft.com> wrote in
message news:19**********************************@microsof t.com...
>I would say not to initialize them as it adds extra code to the
>underlying
> MSIL which in the end takes longer to execute.

Does the JIT generate any code when a field is initialized to its
default
value? (Real question, not rhetorical; I have no idea.)


Yes, it seems to. Here's a quick pair of test programs:

using System;

public class TestWithInit
{
int a0=0, a1=0, a2=0, a3=0, a4=0, a5=0, a6=0, a7=0, a8=0, a9=0;
int b0=0, b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0, b8=0, b9=0;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

and:

using System;

public class TestNoInit
{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestNoInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

On both .NET 2.0 beta 2 and .NET 1.1, the version without explicit
initialisation is faster than the version with initialisation - with or
without optimisation turned on. The difference is actually reasonably
significant - but only in a test where nothing other than object
creation (and GC, obviously) occurs.

I would personally be very reluctant to change any coding habits based
on that though.


Me too (even if my habit weren't to leave such initializations off.)

But I find your results odd; it's a simple enough JIT optimization to
make.

Nov 17 '05 #9
The JIT would have to do this comparison once, at code-generation time,
while the assignment has to be done every time the object is instantiated.
Assuming the JIT has an up-to-date optimizer built it to it, one that does
loop unrolling, common subexpression elimination, peephole optimization (and
probably lots of things invented since I last studied this stuff:-:), it's
doing much more complex transformations than this one.
"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:Ov**************@TK2MSFTNGP12.phx.gbl...
No it's not. The JIT would have to compare each value of the initializer
with the default value, this would take much more time than a simple
assignment.

Willy.

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:OM**************@tk2msftngp13.phx.gbl...

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Mike Schilling <ms*************@hotmail.com> wrote:
"Brian Delahunty" <Br************@discussions.microsoft.com> wrote in
message news:19**********************************@microsof t.com...
>I would say not to initialize them as it adds extra code to the
>underlying
> MSIL which in the end takes longer to execute.

Does the JIT generate any code when a field is initialized to its
default
value? (Real question, not rhetorical; I have no idea.)

Yes, it seems to. Here's a quick pair of test programs:

using System;

public class TestWithInit
{
int a0=0, a1=0, a2=0, a3=0, a4=0, a5=0, a6=0, a7=0, a8=0, a9=0;
int b0=0, b1=0, b2=0, b3=0, b4=0, b5=0, b6=0, b7=0, b8=0, b9=0;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

and:

using System;

public class TestNoInit
{
int a0, a1, a2, a3, a4, a5, a6, a7, a8, a9;
int b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;

static void Main()
{
DateTime start = DateTime.Now;
for (int i=0; i < 100000000; i++)
{
new TestNoInit();
}
DateTime end = DateTime.Now;
Console.WriteLine (end-start);
}
}

On both .NET 2.0 beta 2 and .NET 1.1, the version without explicit
initialisation is faster than the version with initialisation - with or
without optimisation turned on. The difference is actually reasonably
significant - but only in a test where nothing other than object
creation (and GC, obviously) occurs.

I would personally be very reluctant to change any coding habits based
on that though.


Me too (even if my habit weren't to leave such initializations off.)

But I find your results odd; it's a simple enough JIT optimization to
make.


Nov 17 '05 #10

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...

class Foo
{
string s = Bar.s;
public void M1()
{
Console.WriteLine(this.s);
}
}

class Bar
{
internal static string s;
}
class Test
{
static void Main()
{
Foo f1 = new Foo();
f1.M1();
Bar.s = "Hello";
Foo f2 = new Foo();
f2.M1();
}
}
Willy.
Nov 17 '05 #11
Willy Denoyette [MVP] <wi*************@telenet.be> wrote:
"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...


But that's not the same situation. It's one thing for an initializer to
take a value from elsewhere - that has to be done dynamically. It
wouldn't be hard for the JIT to realise that initializers were taking
*constant* values which were also the default ones, and just skip that
initialization step.

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

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:ef**************@tk2msftngp13.phx.gbl...

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...

class Foo
{
string s = Bar.s;
public void M1()
{
Console.WriteLine(this.s);
}
}

class Bar
{
internal static string s;
}
class Test
{
static void Main()
{
Foo f1 = new Foo();
f1.M1();
Bar.s = "Hello";
Foo f2 = new Foo();
f2.M1();
}
}


I don't see any exaxmples there of fields explicitly being set to their
default values, e.g.

int i = 0;

or

String s = null;

*That's* what I'm thinking the JIT could eliminate the code for.
Nov 17 '05 #13

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Willy Denoyette [MVP] <wi*************@telenet.be> wrote:
"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
> The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...


But that's not the same situation. It's one thing for an initializer to
take a value from elsewhere - that has to be done dynamically. It
wouldn't be hard for the JIT to realise that initializers were taking
*constant* values which were also the default ones, and just skip that
initialization step.

I'm having second thoughts now. When do statements like

int i = 0; // i is a field, not a local variable

run? For Java, I know that answer: it's after the superclass is fully
constructed, but before the current class's constructor runs. I'm not sure
about C#, though I presume the answer is similar.

Anyway, how hard is it to prove that the superclass constructor doesn't do
anything that might set a field to a non-default value? Certainly there are
cases where it's easy:

1. The class is a direct child of Object., or
2. The superclass constructor is available to the JIT (as is its superclass
constructor, etc. all the way up) and it calls no virtual methods, does not
pass "this" to any methods, (and does no reflection.

Almost anything else leaves some gap, say that a virtual function overidden
in some derived class sets the field, either by calling another virtual
function or by reflection (or by setting it directly, if it's public or
protected rather than private.)

So (as Dennis Moore said, when the poor he was giving to had become
wealthier than the rich he had taken everything from) this is more
complicated than I had thought..
Nov 17 '05 #14
Mike Schilling <ms*************@hotmail.com> wrote:
I'm having second thoughts now. When do statements like

int i = 0; // i is a field, not a local variable

run? For Java, I know that answer: it's after the superclass is fully
constructed, but before the current class's constructor runs. I'm not sure
about C#, though I presume the answer is similar.
No, it's not quite. In C#, it occurs before the *base* constructor
runs, which makes life much simpler.

<snip>
So (as Dennis Moore said, when the poor he was giving to had become
wealthier than the rich he had taken everything from) this is more
complicated than I had thought..


Fortunately not.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #15
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Willy Denoyette [MVP] <wi*************@telenet.be> wrote:
"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
> The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...


But that's not the same situation. It's one thing for an initializer to
take a value from elsewhere - that has to be done dynamically. It
wouldn't be hard for the JIT to realise that initializers were taking
*constant* values which were also the default ones, and just skip that
initialization step.


Jon, that's right, but this is the job for the language compilers - and
that's been taken care of in C# v2.0 (optimized builds!). I for one would
have prefered that C# did not allowed instance variable initializers at all
and only allowed statics to be initialized that way, just like it's been
done in managed C++.

Willy.
Nov 17 '05 #16

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eR**************@TK2MSFTNGP12.phx.gbl...

"Willy Denoyette [MVP]" <wi*************@telenet.be> wrote in message
news:ef**************@tk2msftngp13.phx.gbl...

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:eo**************@TK2MSFTNGP10.phx.gbl...
The JIT would have to do this comparison once, at code-generation time,


No, it must be done whenever an instance of the class is created, as
guaranteed by the CLI, else this (somewhat contrieved but valid) sample
would fail...

class Foo
{
string s = Bar.s;
public void M1()
{
Console.WriteLine(this.s);
}
}

class Bar
{
internal static string s;
}
class Test
{
static void Main()
{
Foo f1 = new Foo();
f1.M1();
Bar.s = "Hello";
Foo f2 = new Foo();
f2.M1();
}
}


I don't see any exaxmples there of fields explicitly being set to their
default values, e.g.

int i = 0;

or

String s = null;

*That's* what I'm thinking the JIT could eliminate the code for.


Right, Not explicitly but implicitly for the first assignment where Bar.s is
null.
But as I replied to Jon, this is something that should be done by the
language compilers not by the JIT because different languages emit different
initializer constructs in IL, and you can't let them pay for what they don't
need at the JIT level.

Willy.


Nov 17 '05 #17
Jon... Apparently I can call int i; i.ToString() _without_ boxing. This
implies that int i is a struct that does derive from value which derives
from object. I am a bit confused here.

http://www.csharpcorner.com/Code/200...xNUnboxSSF.asp

Regards,
Jeff

Value types *don't* actually derive from anything - only the reference
type which is used for boxing the value type derives (indirectly) from
Object. It's all a bit odd, but is spelled out in the CLI spec.

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #18
Jeff Louie <je********@yahoo.com> wrote:
Jon... Apparently I can call int i; i.ToString() _without_ boxing. This
implies that int i is a struct that does derive from value which derives
from object.
No, it doesn't. It just means that ToString() is overridden in Int32,
so the compiler already knows which version to call - there's no need
to box.

If ToString weren't overridden, it would require a box. Try it with
your own value type and see.
I am a bit confused here.

http://www.csharpcorner.com/Code/200...xNUnboxSSF.asp


That page doesn't load for me, I'm afraid.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #19
Hmm. Do you have an online reference to this part of the CLI spec. I am
begining to think this is a fine semantic argument about the meaning of
"derives from." If int32 honors the contract/interface of object, then
one could argue that it indeed does "derive" from object.

Regards,
Jeff

No, it doesn't. It just means that ToString() is overridden in Int32,
so the compiler already knows which version to call - there's no need
to box.
*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #20
Jeff Louie <je********@yahoo.com> wrote:
Hmm. Do you have an online reference to this part of the CLI spec. I am
begining to think this is a fine semantic argument about the meaning of
"derives from." If int32 honors the contract/interface of object, then
one could argue that it indeed does "derive" from object.


Well, one could argue it, but then one would be ignoring the
definitions of derivation etc :)

In the C# spec, section 14.4.3 (ECMA numbering) it specifies:

<quote>
# If M is an instance function member declared in a value-type:

* E is evaluated. If this evaluation causes an exception, then no
further steps are executed.
* If E is not classified as a variable, then a temporary local
variable of E's type is created and the value of E is assigned to that
variable. E is then reclassified as a reference to that temporary local
variable. The temporary variable is accessible as this within M, but
not in any other way. Thus, only when E is a true variable is it
possible for the caller to observe the changes that M makes to this.
* The argument list is evaluated as described in §14.4.1.
* M is invoked. The variable referenced by E becomes the variable
referenced by this.

# If M is an instance function member declared in a reference-type:

* E is evaluated. If this evaluation causes an exception, then no
further steps are executed.
* The argument list is evaluated as described in §14.4.1.
* If the type of E is a value-type, a boxing conversion (§11.3.1)
is performed to convert E to type object, and E is considered to be of
type object in the following steps. [Note: In this case, M could only
be a member of System.Object. end note]
</quote>

which I think is pretty much what I said - basically, you only need to
box if the method being called isn't actually declared in the value
type.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #21
The best practice is in any case to initialize member variables in the
constructor.

There are some specific behaviors according to the type of the app. In
ASP.Net, for instance, if you initialize the variable within a class and
not within a constructor (page_init) then each time the page loads the
variable will get initialized to that value rather than the current
value. This is also due to the statelessness of the Http protocol.

with regards,
J.V.Ravichandran
- http://www.geocities.com/
jvravichandran
- http://www.411asp.net/func/search?
qry=Ravichandran+J.V.&cob=aspnetpro
- http://www.southasianoutlook.com
- http://www.MSDNAA.Net
- http://www.csharphelp.com
- http://www.poetry.com/Publications/
display.asp?ID=P3966388&BN=999&PN=2
- Or, just search on "J.V.Ravichandran"
at http://www.Google.com

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #22
Ravichandran J.V. <jv************@yahoo.com> wrote:
The best practice is in any case to initialize member variables in the
constructor.
I disagree - I tend to prefer to do it at the variable declaration if
it's going to be the same value whichever constructor is invoked.
There are some specific behaviors according to the type of the app. In
ASP.Net, for instance, if you initialize the variable within a class and
not within a constructor (page_init) then each time the page loads the
variable will get initialized to that value rather than the current
value. This is also due to the statelessness of the Http protocol.


But page_init is not the constructor for the class, as I *think* you
were implying it was. (If you weren't, please explain the middle
sentence above - it doesn't make much sense at the moment.)

Except in a few *very* unusual circumstances, leaving the values as the
default ones, explicitly setting those values in the constructor, and
explicitly setting those values in the variable declarations will all
have the same effect.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #23
Jon... If this means M(E) I wonder if this is just saying that if M is
declared in a
reference type and is passed E that is a value type, then E will be
boxed. So
System.Console.WriteLine(valueType) valueType is boxed whereas
valueType.ToString() there is no boxing. Either way all valueTypes honor
the
ToString() method which appears to represent polymorphic behavior.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #24
Jeff Louie <je********@yahoo.com> wrote:
Jon... If this means M(E) I wonder if this is just saying that if M is
declared in a reference type and is passed E that is a value type,
then E will be boxed.
No, it's not M(E). If you look at the bit of the spec I was referring
to, E is the instance expression - i.e. what the method is going to be
invoked *on*.
So System.Console.WriteLine(valueType) valueType is boxed whereas
valueType.ToString() there is no boxing. Either way all valueTypes honor
the ToString() method which appears to represent polymorphic behavior.


No, the value types themselves don't honour ToString - their boxed
equivalents do, because the boxed types derive (indirectly) from
Object.

The difference here is that C# contrives to make it look like value
types derive from Object indirectly, but the CLR doesn't - and IMO it's
important to know the difference. Indeed, the C# spec actually refers
to value types deriving from Object implicitly, which I think is part
of the problem - it's a bad way of specifying the language, as it hides
the nature of value types as far as the CLR is concerned. I wouldn't be
surprised if analysing the C# spec closely would throw up some
inconsistencies due to this.

Take, for example, section 8.2.4 (which is part of section 8 which is
only a note, admittedly) - it states: "An int value can be converted to
object and back again to int". If int actually derives from object,
there shouldn't be any conversion necessary, just as it would make no
sense to talk about converting a string to an object.

Put it this way - while the CLR explanation (with its boxed type of the
same name business) is slightly more complicated at first sight, it's a
lot simpler in the long run. You don't need to treat inheritance with
value types as different from inheritance with reference types, because
you just state that there *is* no inheritance with value types.

It's a little bit like my old bugbear of people saying that objects are
passed by reference - it's supposedly a simplification, but the hoops
you have to jump through just to avoid stating the truth aren't worth
it IMO.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #25
Hi Jon... This looks more like "ad-hoc" polymorphism as opposed to
"subclass"
polymorphism where the compiler may need to convert/coerce the valueType
to
a reference type and call ToString() on the reference.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #26
Jeff Louie <je********@yahoo.com> wrote:
Hi Jon... This looks more like "ad-hoc" polymorphism as opposed to
"subclass"
polymorphism where the compiler may need to convert/coerce the valueType
to
a reference type and call ToString() on the reference.


Exactly. But when ToString() is actually declared in the value type as
well, rather than getting the Object (or System.ValueType)
implementation, no boxing is required.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #27
Jon.. Thanks for your help.

Regards,
Jeff

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #28

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Jeff Louie <je********@yahoo.com> wrote:
Hi Jon... This looks more like "ad-hoc" polymorphism as opposed to
"subclass"
polymorphism where the compiler may need to convert/coerce the valueType
to
a reference type and call ToString() on the reference.


Exactly. But when ToString() is actually declared in the value type as
well, rather than getting the Object (or System.ValueType)
implementation, no boxing is required.


Is

public String ToString() { return base.ToString();}

an optimization, or does the base call require boxing?
Nov 17 '05 #29
Mike Schilling <ms*************@hotmail.com> wrote:

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Jeff Louie <je********@yahoo.com> wrote:
Hi Jon... This looks more like "ad-hoc" polymorphism as opposed to
"subclass"
polymorphism where the compiler may need to convert/coerce the valueType
to
a reference type and call ToString() on the reference.


Exactly. But when ToString() is actually declared in the value type as
well, rather than getting the Object (or System.ValueType)
implementation, no boxing is required.


Is

public String ToString() { return base.ToString();}

an optimization, or does the base call require boxing?


Good question. Not sure, but I suspect it involves a box. The easiest
thing would be to try it an look at the IL :)

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

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Mike Schilling <ms*************@hotmail.com> wrote:

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
> Jeff Louie <je********@yahoo.com> wrote:
>> Hi Jon... This looks more like "ad-hoc" polymorphism as opposed to
>> "subclass"
>> polymorphism where the compiler may need to convert/coerce the
>> valueType
>> to
>> a reference type and call ToString() on the reference.
>
> Exactly. But when ToString() is actually declared in the value type as
> well, rather than getting the Object (or System.ValueType)
> implementation, no boxing is required.


Is

public String ToString() { return base.ToString();}

an optimization, or does the base call require boxing?


Good question. Not sure, but I suspect it involves a box. The easiest
thing would be to try it an look at the IL :)


You asked for it: :-)

public struct HasOverride {
public int i;

public override String ToString() {
return base.ToString();
}
}

results in:

..method public hidebysig virtual instance string
ToString() cil managed
{
// Code size 21 (0x15)
.maxstack 1
.locals init ([0] string CS$00000003$00000000)
IL_0000: ldarg.0
IL_0001: ldobj HasOverride
IL_0006: box HasOverride
IL_000b: call instance string
[mscorlib]System.ValueType::ToString()
IL_0010: stloc.0
IL_0011: br.s IL_0013
IL_0013: ldloc.0
IL_0014: ret
} // end of method HasOverride::ToString

So your suspicion is correct.
Nov 17 '05 #31

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

Similar topics

0
1780
by: BCC | last post by:
I have some c++ code like this: class MyObject { public: int m_a; int m_b; int m_c; // etc. etc. } And in an XML file I have something like this:
4
2287
by: Avner Flesch | last post by:
Hi, Do you know how can I intialize an array member: for example class A { public: A(int x); };
10
3503
by: Fred Ma | last post by:
Are there any reasons that would make it bad for C++ to allow simultaneous declaration and initilization of member data? Current way: ------------ class DerivedClass : BaseClass { { enum {...
4
4716
by: Steven T. Hatton | last post by:
I mistakenly set this to the comp.std.c++ a few days back. I don't believe it passed the moderator's veto - and I did not expect or desire anything different. But the question remains: ISO/IEC...
5
4546
by: Jim Langston | last post by:
What I want to do: have a vector of ints in my class initialized with 0 to 499 which will later be pushed/popped out of the vector by instances. What I have: class CParticleStream // Yes, I...
3
1583
by: KK | last post by:
Hello all, I have several classes binded by one common interface - say 'sum' interface which calculates the sum of all the class elements of type 'int'. class Alphabet { int _a; int _b; int...
2
2809
by: Vinu | last post by:
Hi, I am facing one problem related to global variables in .so file. When ever I access the variable the application is crashing I have a class called services. class services { services(){...
6
19162
by: nik | last post by:
hello friends, a class having two const variables ,how can we initialize these variables
3
2040
by: digz | last post by:
This is a very simplified version of something I am trying to understand. The State object holds the strings and maps , and I pass a reference to State to the process Function which manipulates it...
0
7237
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,...
0
7137
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...
0
7347
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7506
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5656
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,...
1
5062
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...
0
3207
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
779
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
443
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...

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.