473,761 Members | 2,410 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct with string, where does it allocate to? heap?

Hi,

As it is always stated that value type is allocated on stack, while
reference types are on managed heap. How about the struct with
string members?
stuct A { string str; }

String type is considered as reference type.... My guess is the
struct A is actually a valuetype with a string reference/address.
So it acts as if struct A { int ptrStr; } Anyway, the ptrStr is like a
pointer (integer value) to a non-mutable reference string on heap.

Some suggestions? How does it work? Under GC, does all copies
of A gets updated with the string reference value?

Mar 27 '06 #1
4 6195
using System;

using System.Collecti ons.Generic;

using System.Text;

namespace construct

{

class Program

{

public struct A

{

private string str;

public string Str

{

set { this.str = value; }

get { return this.str; }

}

}

public class B

{

private string str;

public string Str

{

set { this.str = value; }

get { return this.str; }

}

}

public static void fooA(A a)

{

a.Str = "Assigned FooA";

}

public static void fooB(B b)

{

b.Str = "2";

}

static void Main(string[] args)

{

A ast = new A();

B bst = new B();

ast.Str = "1";

fooA(ast);

fooB(bst);

System.Console. WriteLine(ast.S tr);

System.Console. WriteLine(bst.S tr);

System.Console. ReadLine();

}

}

}
---- Looks like it does allocate on stack

Mar 27 '06 #2
> As it is always stated that value type is allocated on stack, while reference types are on managed heap.

A lot of books state this. It is an oversimplificat ion. The truth is:

1. Reference types are allocated on the managed heap.
2. Value types that are local variables or method parameters are
allocated on the stack. This includes references to reference types
(which are, themselves, just values).
3. Value types that are members of a reference type (for example the
"int"s that form part of an object's state) are allocated along with
and in-line with all of the other data for the reference type, on the
managed heap.

Your assumption about a value type that contains a reference to a
string is correct: the values that make up the value type will be
allocated wherever that value type is allocated. If it is a local
variable or a method parameter, on the stack. If it is a member in a
class definition, then on the heap with the rest of the data for the
class.

The value type will contain as part of its value a reference to the
string, which will be allocated on the managed heap.

Remember that strings are immutable, so one cannot make a change to the
string and have all value types that reference it change together,
although your assumption that all value types point to the same string
on the heap would be true (depending upon how the string was
constructed and how its reference is placed in the struct).

Your theory works out better if you choose something other than a
string. Take, for example, a value type that is a Measure:

public struct Measure
{
private decimal _quantity;
private UnitOfMeasure _units;

public Measure(decimal quantity, UnitOfMeasure units)
{
...
}
}

Assuming that UnitOfMeasure is a reference type, then the struct will
contain: a decimal value, and a reference. If multiple Measures are
constructed pointing to the same UnitOfMeasure, then they all contain
the same reference to the same unit of measure object on the managed
heap.

If the UnitOfMeasure class were mutable (a bad idea, in this case, but
say it were) then a change to a unit of measure object would have an
effect in all Measure structs that point to it, just as you surmised.
That's why I made my UnitOfMeasure class immutable. :)

Mar 27 '06 #3
Really appreciate... thx!!

Mar 27 '06 #4
using System;

using System.Collecti ons.Generic;

using System.Text;

namespace construct

{

class Program

{

public class IntClass

{

private int x;

public IntClass() { x = 0; }

public int Val { get { return x; } set { x = value; } }

}

public struct A

{

private IntClass xint;

public void setInt() { xint = new IntClass(); }

public IntClass XInt

{

set { this.xint = value; }

get { return this.xint; }

}

public int X

{

set { xint.Val=value; }

get { return xint.Val; }

}

}

public static void fooA(A a)

{

a.XInt = new IntClass();

}

static void Main(string[] args)

{

A a = new A();

a.setInt();

a.X = 6;

fooA(a); // should still be 6;

System.Console. WriteLine(a.X); //6

A b = a;

b.X = 5;

System.Console. WriteLine(a.X); // both to 5
System.Console. WriteLine(b.X); // both to 5

b.XInt = new IntClass(); // the reference wont get updated into all
copies of the value types.
System.Console. WriteLine(a.X); // 5
System.Console. WriteLine(b.X); // 0

System.Console. ReadLine();

}

}

}

Mar 27 '06 #5

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

Similar topics

0
1764
by: Uday Deo | last post by:
Hi everyone, I have a .NET app invoking from the ASP page. It has to load bunch of data during first visit. The app works fine on the Staging and Prod server. This is the first time the company got the separate machine as a Development server. I have installed .NET Visual studio and framework on the machine. I copied all the files and necessary information from staging to the development box. I am getting the following error while...
5
8180
by: Alfonso Morra | last post by:
Hi, Doest the c_str() method of the string class allocate memory. if it does alloc mem behind the scenes - whose responsibility is it to cleanup after (i.e. free the returned char*?) Tkx
0
2754
by: AshleyT | last post by:
I am trying to get the user authenticated name and then get the last 3 digits of that string. Below is the first part of my code. Do I need to do this in a class, or namespace? It seems that I am missing something to use this code. The current error I get is: 'string' does not contain a definition for 'length' Thanks for any help. <%@ Page Language="C#" %> <%@ Import Namespace="System.Collections" %>
0
5032
by: Gaurav | last post by:
Hi, I have a connection string "Data Source=db1.mynet;DATABASE=test;User ID=testuser;Password=test;" , when i use the connection string to get a dataset of all the tables of a database it works without any problem, but when i try and call a stored procedure i get an exception trace like :
1
32447
by: openleren | last post by:
Hi all, with a little help from my friends, I am trying to construct a connectionstring from a relative path in web.config. It contains <add key="conAccess" value="microsoft.jet.oledb.4.0;data source=data/database.mdb" /> In my webform I constructed a fucntion Public Function getConnectionString() As String
0
1544
by: andy | last post by:
Hi all, Any help much appreciated - Andy I am trying to connect to a SQL Server DB using c#, ADO.Net mySqlConnection = new SqlConnection(@"user=ddd;password=€jfn¾;server=srv5;Trusted_Connection=no;database=dan"); as you can see there are "special" ASCII chars in the user and password
1
2643
by: sal | last post by:
Greets, All Question with udl and connection string does it work? I'm having problems with the code below I keep getting an error "Keyword not supported 'File Name'" I was just following app.dev cbt course and for some reason it doesn't work for me does someone know what I doing wrong
2
2990
by: lovecreatesbea... | last post by:
If the built-in operator keyword new doesn't allocate memory on heap and it calls global operator new (::operator new) or class member operator new to do that. What are the two kinds of operator new used to allocate heap memory? Before there aren't global and member operator new, the built-in operator keyword new does really allocate heap memory, right?
19
8950
by: SPABBOJU | last post by:
Hi guys... I want to check whether string does not exist with out using !~ . basical for character we check like that using . How to do the same for word, sentence ?.... I actually need as a part of one of my project Thank you,
1
2144
by: lye85 | last post by:
#include <stdio.h> #include <stdlib.h> #include <string.h> struct account { char AccName; int Age; double AccBalance; struct account *Next;
0
9353
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,...
0
10123
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9975
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9909
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8794
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7342
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
5241
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...
1
3889
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
3
3481
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.