473,883 Members | 1,566 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

int number = new int();

Hello!

If I write this statement
int number = new int();
I don't get compiler error or run time error
but how will the compiler read such a statement ?

For example will number be a reference to a new int on the heap?

//Tony

Sep 26 '08
28 9111
Jon Skeet [C# MVP] kirjoitti:
OD <OD <webmaster @ e-naxos dot com>wrote:
>Why can't you just say "ok, i was wrong" ?

Because I don't think I was. The "value types are on the stack;
reference types are on the heap" is a myth which confuses people. I try
to set the record straight. I've helped a number of people on this
matter. Why would I now say I was wrong, if I still don't believe I
was?
I think OD is right. When the program sees int, it is always a value
that comes from the stack. There is something on heap that is boxed or
inside a class, but the new int (like the original message asked) is
created onto stack.

--
Arto Viitanen
Sep 29 '08 #21
Peter Duniho <Np*********@nn owslpianmk.comw rote:
Right. Not only is it dangerous in terms of multiple threads, but even
in a single thread I don't see how it could work.

Do you mean in theory? Or based on some specifics about how the CLR works?

To me, it's obvious in theory how it'd work. But I don't know enough
about the CLR to know whether it'd support that sort of thing. It may be
that in any language, you have to use pointers rather than references to
implement the behavior.
Well, consider this program:

class Test
{
public static void Main()
{
Action foo = Foo();
foo();
}

public static Action Foo()
{
int i = 5;
return Bar(ref i);
}

public static Action Bar(ref int x)
{
return (Action) delegate()
{
x++;
Console.WriteLi ne(x);
}
}
}

What would you expect running that to do? I can't see how it can
compile and run without blowing up (or being unpredictable). The
variable x can't be captured in the normal way, because effectively the
variable itself is being passed in (rather than an initial value).
[...]
Exactly. Both the caller and the callee would need to be using unsafe
code, and explicitly handle the pointers. My point is that you're
unlikely to *accidentally* get into this situation.

Well, it seems to me that there's a broad gap between "accidently
implemented" and "nasty hack". That was the gist of my comment. I agree
it'd be a hack, but I've seen far nastier (probably been responsible for a
few over the years, for that matter...not that I'm proud of that :) ). I
was mostly just curious what your threshold for "nasty hack" is...sounds
like it's pretty low. :) (Not that there's anything wrong with that...to
each their own).
Well, anything involving pointers would make me suspicious to start
with - and anything relying on a particular stackframe in one thread
still being around by the time another thread executed some code just
sounds pretty evil to me.

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Sep 29 '08 #22
On Sun, 28 Sep 2008 22:11:21 -0700, Arto Viitanen
<ar***********@ microteam.fiwro te:
Jon Skeet [C# MVP] kirjoitti:
>OD <OD <webmaster @ e-naxos dot com>wrote:
>>Why can't you just say "ok, i was wrong" ?
Because I don't think I was. The "value types are on the stack;
reference types are on the heap" is a myth which confuses people. I try
to set the record straight. I've helped a number of people on this
matter. Why would I now say I was wrong, if I still don't believe I was?
I think OD is right.
That would be a mistake on your part.
When the program sees int, it is always a value
that comes from the stack.
That's simply not true. Nor do I believe that's what OD was writing.
There is something on heap that is boxed or
inside a class, but the new int (like the original message asked) is
created onto stack.
There's no such thing as a "new int". As in the original question, it's
simply a notation that represents the default value for the type. It
doesn't reside anywhere until it's copied to a variable, and where it
resides depends on the variable to which it's copied. It is _not_
"created onto stack" unless the destination is itself on the stack.

In particular, if the variable is part of a reference type (i.e. is a
member field), then the instance of the reference type is stored on the
heap, and the member field contained by that instance is as well. The
stack need never be involved.

Even in the original question, you cannot claim that the int is copied to
a stack variable, because the original poster didn't provide us with
enough detail to know where his "int number" is declared.

Even if you buy the person posting as "OD"'s claim that when a value type
is part of another value that's on the heap, it is "not really and
directly on the heap by itself" (a silly statement, IMHO), it's a long way
from that to claiming that all value types are stored on the stack. Even
"OD" isn't going that far, as near as I can tell.

Pete
Sep 29 '08 #23
On Sep 29, 6:11*am, Arto Viitanen <arto.viita...@ microteam.fiwro te:
I think OD is right. When the program sees int, it is always a value
that comes from the stack.
No, that's not true. Consider:

public class Foo
{
int x;

public void Bar()
{
int y = x;
}
}

Now, where does the value y is initialized with come from? The heap -
because that's where the value of x is stored.
There is something on heap that is boxed or
inside a class, but the new int (like the original message asked) is
created onto stack.
The right hand side of the statement in the original question is
(logically, at least) evaluated on the stack. But the target of the
assignment could well be on the heap.

Let's go back to Cor's original statement which I disagreed with:
"Int32 is a structure they never are placed on the heap."

Now consider the class above again:
1) What is the type of the variabe x?
2) Where does its value live, i.e. where is it "placed"?

My answers are "int, i.e. Int32" and "on the heap" - which directly
contradicts Cor's statement.

What are your answers to the above two questions?

Jon
Sep 29 '08 #24
On Sep 29, 6:11*am, Arto Viitanen <arto.viita...@ microteam.fiwro te:
I think OD is right. When the program sees int, it is always a value
that comes from the stack.
No, that's not true. Consider:

public class Foo
{
int x;

public void Bar()
{
int y = x;
}
}

Now, where does the value y is initialized with come from? The heap -
because that's where the value of x is stored.
There is something on heap that is boxed or
inside a class, but the new int (like the original message asked) is
created onto stack.
The right hand side of the statement in the original question is
(logically, at least) evaluated on the stack. But the target of the
assignment could well be on the heap.

Let's go back to Cor's original statement which I disagreed with:
"Int32 is a structure they never are placed on the heap."

Now consider the class above again:
1) What is the type of the variabe x?
2) Where does its value live, i.e. where is it "placed"?

My answers are "int, i.e. Int32" and "on the heap" - which directly
contradicts Cor's statement.

What are your answers to the above two questions?

Jon
Sep 29 '08 #25
On Sep 29, 7:06*am, "Jon Skeet [C# MVP]" <sk...@pobox.co mwrote:
On Sep 29, 6:11*am, Arto Viitanen <arto.viita...@ microteam.fiwro te:
I think OD is right. When the program sees int, it is always a value
that comes from the stack.

No, that's not true. Consider:
<snip>

Apologies for the double post. Not sure what happened there...

Jon
Sep 29 '08 #26
On Sun, 28 Sep 2008 22:32:32 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
Right. Not only is it dangerous in terms of multiple threads, but even
in a single thread I don't see how it could work.

Do you mean in theory? Or based on some specifics about how the CLR
works?
[...]

Well, consider this program:

class Test
{
public static void Main()
{
Action foo = Foo();
foo();
}
public static Action Foo()
{
int i = 5;
return Bar(ref i);
}
public static Action Bar(ref int x)
{
return (Action) delegate()
{
x++;
Console.WriteLi ne(x);
}
}
}

What would you expect running that to do?
I expect running that would do exactly what you'd expect it to do.
I can't see how it can
compile and run without blowing up (or being unpredictable).
The code you posted can't, I agree. Code that captures a by-reference
variable would have to ensure that it gets used only when the variable is
still present on the stack. Likewise, code that would reference one
thread's stack from another thread would indeed have to be careful to
preserve the stack variable until it's sure the other thread is done using
it.

In C#, it makes perfect sense to prohibit this sort of scenario except in
unsafe code. In C#, one fundamental assumption in the language is that
the language prevents you from accessing invalid data. Whatever else
happens, you can always be assured that the simple act of accessing a
variable isn't going to blow up. But this isn't about what C# _does_ do.
It's about what it might do given alternate rules of engagement.

And given those alternate rules of engagement, it's obvious what it would
mean to access in one thread a by-reference argument passed in another
thread.

That's why I asked the question "Do you mean in theory?" It wasn't clear
to me from your statement "I don't see how it could work" whether you mean
"...in C#", "...in a .NET program", or "...in a hypothetical language that
supports closures, passing by reference, and capturing a by-reference
argument".
The
variable x can't be captured in the normal way, because effectively the
variable itself is being passed in (rather than an initial value).
The language _could_ capture the variable "in the normal way", modulo an
extension of the language that allows it. That is, it could encapsulate
the pointer that a by-reference argument already encapsulates, preserving
it for later use.

Sure, that'd be against C#'s rules, or at the very least, there'd also
have to be some run-time support that has a way of checking to make sure
the referenced variable still exists so that an exception can be thrown if
an invalid attempt to access the variable is made.

But that's very different from saying it simply can't be done.

The bottom line: you can already do the exact same thing using unsafe
code. So obviously, the language and run-time _could_ do something
similar if it fit within the desired design (I'm sure it doesn't fit, but
again...I'm talking about what could happen, not what should happen).

An alternative approach would be to extend the concept of variable
capturing to address the potential of a captured by-reference argument.
It'd be unduly complicated, but it could be done (basically, when
capturing a by-ref argument, the run-time would have to create a captured
data structure that references the existent variable passed by-reference
until that variable no longer exists, at which point the run-time would
copy it to a more conventional captured-variable data structure).

So, that's at least two different approaches that could be used, one of
which would fit fine into the expected behavior of C#. It could be
considered an overcomplicatio n of the language and run-time, but then
there are some pretty complicated "syntactic sugars" in C# (witness
enumerators).
[...]
Well, anything involving pointers would make me suspicious to start
with - and anything relying on a particular stackframe in one thread
still being around by the time another thread executed some code just
sounds pretty evil to me.
For better or worse, .NET already has a specific example that deals with
that situation just fine: Control.Invoke( ).

The need to execute some specific code on some specific thread is
uncommon, but it does exist. Using normal synchronization mechanisms,
it'd be possible to write code that safely references variables from one
thread's stack in another thread. Is it a "pretty evil hack" for
Control.Invoke( ) to deliver some code to be executed on one thread, while
it blocks another? That sort of synchronization is all it'd take to
safely use by-reference variables cross-thread. And that's assuming no
language support such as the hypothetical behaviors I've mentioned above.

Pete

p.s. As if all of the above wasn't enough, now I'm sitting here curious
what happens if you pass by-reference a member field of a class. Does the
by-reference argument preserve a reference to the instance of the class
that contains the field? If not, how does C# ensure that the instance
isn't GC'ed before it's done with the by-reference argument? A quick test
suggests that the reference to the containing instance _is_ kept
somewhere, but I haven't had time to research how that happens or why
(i.e. whether it's stipulated in the C# spec).

For example:

class A
{
public int i;
}

void MethodA()
{
A[] rga = new A[1];

rga[0] = new A();
rga[0].i = 5;

MethodB(rga, ref rga[0].i);
}

void MethodB(A[] rga, ref int i)
{
rga[0] = null;
GC.Collect();
Console.WriteLi ne(i);
}

Interestingly, assuming C# does do this "reference the containing
instance" behavior, it's actually in the same vein as the "safely capture
a by-reference argument" implementation I outlined above. That is, the
compiler has to do some extra work to see where a particular value came
from and handle it accordingly.
Sep 29 '08 #27
On Sep 29, 7:23*am, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:

<snip.
I can't see how it can
compile and run without blowing up (or being unpredictable).

The code you posted can't, I agree. *Code that captures a by-reference *
variable would have to ensure that it gets used only when the variable is*
still present on the stack. *Likewise, code that would reference one *
thread's stack from another thread would indeed have to be careful to *
preserve the stack variable until it's sure the other thread is done using *
it.

In C#, it makes perfect sense to prohibit this sort of scenario except in*
unsafe code. *In C#, one fundamental assumption in the language is that*
the language prevents you from accessing invalid data.
Exactly - and that's what I meant by "I don't see how it could work."
To expand that, "I don't see how it could be permitted and still
remain true to the spirit of C#" :)
>*Whatever else happens, you can always be assured that the simple
act of accessing a variable isn't going to blow up. *But this isn't about
what C# _does_ do. It's about what it might do given alternate rules
of engagement.
True - but when considering "what if we could do X" I usually assume
that the core tenets of the language are adhered to. Anyway, so long
as we understand each other now it doesn't matter too much.

One interesting point would be whether such a program was verifiable.
I haven't looked closely at the verifiability rules. I might do so...

<snip possible approaches - I have nothing more to add there>
[...]
Well, anything involving pointers would make me suspicious to start
with - and anything relying on a particular stackframe in one thread
still being around by the time another thread executed some code just
sounds pretty evil to me.

For better or worse, .NET already has a specific example that deals with *
that situation just fine: Control.Invoke( ).
Does that really rely on any particular stackframe? In particular, if
the calling thread is interrupted or aborted, I wouldn't expect the UI
thread to suffer corruption - or vice versa. But I do see what you're
getting at, I think.
The need to execute some specific code on some specific thread is *
uncommon, but it does exist. *Using normal synchronization mechanisms, *
it'd be possible to write code that safely references variables from one *
thread's stack in another thread. *Is it a "pretty evil hack" for *
Control.Invoke( ) to deliver some code to be executed on one thread, while*
it blocks another? *That sort of synchronization is all it'd take to *
safely use by-reference variables cross-thread. *And that's assuming no*
language support such as the hypothetical behaviors I've mentioned above.
Well, it intertwines the threads more tightly than is the case now -
making situations like the above more risky. In the Control.Invoke
situation we're certainly blocking one thread based on another, but
the actual stackframes are still isolated which limits possible
damage. As soon as one stackframe "going away" puts another thread at
risk of corruption, the platform feels less stable.
p.s. *As if all of the above wasn't enough, now I'm sitting here curious *
what happens if you pass by-reference a member field of a class. *Does the *
by-reference argument preserve a reference to the instance of the class *
that contains the field? *If not, how does C# ensure that the instance *
isn't GC'ed before it's done with the by-reference argument? *A quick test *
suggests that the reference to the containing instance _is_ kept *
somewhere, but I haven't had time to research how that happens or why *
(i.e. whether it's stipulated in the C# spec).
Hmm. Interesting question. I really don't know how that's handled.
I'll have a look into it - and see whether the book I'm reading at the
moment (CLR via C#) covers it. (If any non-spec book covers it,
this'll be the one :)

Jon
Sep 29 '08 #28
On Mon, 29 Sep 2008 01:08:10 -0700, Jon Skeet [C# MVP] <sk***@pobox.co m>
wrote:
Exactly - and that's what I meant by "I don't see how it could work."
To expand that, "I don't see how it could be permitted and still
remain true to the spirit of C#" :)
Okay...that answers my question for clarification of your statement.
Thanks.
[...]
Does that really rely on any particular stackframe? In particular, if
the calling thread is interrupted or aborted, I wouldn't expect the UI
thread to suffer corruption - or vice versa. But I do see what you're
getting at, I think.
I think you do. :) No, AFAIK Control.Invoke( ) doesn't currently have any
dependency on a particular stack frame. My only point was that we already
have scenarios in which one thread has a mandate to wait on another. It
does come up, and it's a manageable problem. Yes, with Control.Invoke( )
doing so doesn't involve a dependency on the stack, but a program could
have other reasons for relying on the synchronization (i.e. it's not just
a matter of convenience).

Sometimes threads need to wait on others. :)
Well, it intertwines the threads more tightly than is the case now -
making situations like the above more risky.
Yup, true. With great power comes great responsibility. :)
In the Control.Invoke
situation we're certainly blocking one thread based on another, but
the actual stackframes are still isolated which limits possible
damage. As soon as one stackframe "going away" puts another thread at
risk of corruption, the platform feels less stable.
Well, that's why I think if something like this ever showed up in C#, it'd
have to be implemented in a way that removes the dependency on the stack
frame itself. I agree the alternative wouldn't be appropriate in C#.
>p.s. ¬*As if all of the above wasn't enough, now I'm sitting here
curious ¬*
what happens if you pass by-reference a member field of a class. ¬*Does
the ¬*
by-reference argument preserve a reference to the instance of the class
that contains the field? ¬*If not, how does C# ensure that the instance ¬*
isn't GC'ed before it's done with the by-reference argument? ¬*A quick
test ¬*
suggests that the reference to the containing instance _is_ kept ¬*
somewhere, but I haven't had time to research how that happens or why ¬*
(i.e. whether it's stipulated in the C# spec).

Hmm. Interesting question. I really don't know how that's handled.
I'll have a look into it - and see whether the book I'm reading at the
moment (CLR via C#) covers it. (If any non-spec book covers it,
this'll be the one :)
I look forward to hearing whatever you find. It's an intriguing detail I
never thought about before.

Pete
Sep 29 '08 #29

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

Similar topics

6
10272
by: moi | last post by:
hi, i have an assignment to put 6 pseudo random numbers into an array to simulate drawing 6 lottery numbers between 1-49. the code i have to do this so far is listed below. i dont think its far off. im getting a recurring error regarding the syntax of my main() function argument calling in lottery_numbers array. so any help as to whats glaringly going wrong here?? oh and some brief guidance on whats the easiest way to sort the numbers...
4
2705
by: Jack | last post by:
I have two files: sort_comparison.c++ my_sort.h sort_comparison.c++ calls this code in my_sort.h: void my_sort::fillArray(int arr,int n) { // const int random_number_range=1000000;
23
5299
by: Davey | last post by:
How do I display an integer in binary format in C? e.g. 4 displayed as "100"
19
4464
by: gk245 | last post by:
Trying to write a program that will figure out if a number is perfect or not. Here is my logic: 1) Read in the number 2) Split it up (number - 1) 3) Put all the split up numbers into an array 4) Figure out if the original number is evenly divisible by any of the numbers in the array.
4
5230
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime and 0 if it isn't. I have spent ages just getting this code to work and i'm worried i need to rip it to bit to get this function to work ! The function is: int prime(int number) here is my code so far: #include...
4
2332
by: cnixuser | last post by:
Hello, I am attempting to create a prime number detector that will identify all of the prime numbers within a specified range of numbers. The problem is, for some reason my program is not detecting any prime numbers and seems to be only to be printing one value of zero from the array that I am trying to store the prime numbers detected in. I believe the zero is coming from the value already stored in the array when I initialzed it, which means...
11
12354
by: davidj411 | last post by:
i am parsing a cell phone bill to get a list of all numbers and the total talktime spend on each number. i already have a unique list of the phone numbers. now i must go through the list of numbers and add up the totals for each number. on the bill, each line has a few fields,one field containing the phone number, another field containing the number of minutes on that call. the bill is comma delimited.
14
19087
by: Tommy Jakobsen | last post by:
Hi. Is there a method in .NET that takes "year" as an argument and returns the total number of weeks in that year? For culture da-DK (Danish). Thanks in advance. Tommy.
2
5486
by: alishaikhji | last post by:
I am working on a program which will need several different integer and float random numbers at different stages, for example: - At one point, I need a random number (float) in the range 0.1 to 10.0 - At one point, I need a random number (float) in the range 0.5 to 1.5 - At one point, I need a random number (float) in the range 0.3 to 3.0 - At one point, I need a random number (float) in the range 0.1 to 10.0 Also, I need to make it sure...
0
9932
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 usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9777
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
7957
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7114
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5782
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5979
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4602
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
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3226
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.