String Reference Type

R

RN1

If I am not mistaken, String is reference type. Can someone please
explain me why is it reference type & not value type?
 
J

Jonathan Wood

A string can potentially contain a lot of data, and there's no telling what
size a particular string might need to be.

Therefore, not only does it make little sense to try and store a string in a
register or on the stack, or anything else you'd do with a value type,
strings have always been pointers in traditional languages.

Why would it be a value type?
 
R

RN1

A string can potentially contain a lot of data, and there's no telling what
size a particular string might need to be.

Therefore, not only does it make little sense to try and store a string ina
register or on the stack, or anything else you'd do with a value type,
strings have always been pointers in traditional languages.

Why would it be a value type?

--
Jonathan Wood
SoftCircuits Programminghttp://www.softcircuits.com






- Show quoted text -

So does it mean that data types that don't have a fixed size are
reference types & those having a fixed size are value types?

Thanks,

Ron
 
L

Lars

Hi

No, Strings in Pascal (and ADA as I reacll) are tru types. When Delphi
started uses longer strings thye implemented it with a reference but you
never see that. You can still use call by value for a 3456 character long
string. But the string is probably copied into a temporarilly string much as
a ansi C++ template string would do with the default and copy contructors.

String myStringFunc( S: String )
begin
myStringFunc := S + S;
(* If S is longer than 128 chars then the returning string is
cut at pos 255 (position) holds the length of the string.
Parameter S is unchanged since it is a call by value and the
parameter
is copied into S which is on the stack
*)
end;

String myStringFunc( var S: String )
begin
myStringFunc := S + S;
(* If S is longer than 128 chars then the returning string is
cut at pos 255 (position) holds the length of the string.
Parameter S is canged since it is a call by referencek
*)
end;


C++ code

//
// String is a predefined class written some where
//
// I recall Visal C++ uses CString for strings and BC Builder uses
// same strings types as Delphi since BC Builders VCL code is written
// in Delphi. Both BCB and Delphi uses the same backend compiler
//
String myFunc( String S )
{
return S & S;
// Weather the values in the input parameter is changed or no
// depends on how the copycontructor and default contructos
// is defined. Weather the class String uses deep copy or shallow copy
// for the constructors.
//
// If the copy contructor inludes s reference member in stead of a
pointer
// char& in stead of char*
// This code fails to compile unless you have written the default and
copy contructors.
// THAT IS WHYYOU ALWAYS SHOULD USE refernences "&" NOT pointerrs
// "*" IN C++ CLASSES!
// Then you MUST define the default and copy constructors.
//
}

String& myFunc( String& S )
{
return S & S;
// S is changed weather the actual storing is changed or not depends
// on how the copy contructor was written (constructor String( String&
S ); )
// The result is copied into another string object. How that is done is
also
// depndant of now the copy contructor was writte.

// If the copy contructor inludes s reference member in stead of a
pointer
// char& in stead of char*
// This code can be copmiled. The paremeter in is the parameted send
out
// same as String* myFunc( String* S );
}


Don't know about C# but I hope the compiler takes care of this. By
references or not is not of interest. What is of interest is if you have the
option to use call by value for strings or if all parameters are treated as
references. Can you use call by value in C# how do you use call by value?


Lars
 
J

Jonathan Wood

No, I gave two issues: Variable size was one but the potential to be large
was the other. This are two issues that are likely to make a type a
reference type.

--
Jonathan Wood
SoftCircuits Programming
http://www.softcircuits.com


A string can potentially contain a lot of data, and there's no telling
what
size a particular string might need to be.

Therefore, not only does it make little sense to try and store a string in
a
register or on the stack, or anything else you'd do with a value type,
strings have always been pointers in traditional languages.

Why would it be a value type?

--
Jonathan Wood
SoftCircuits Programminghttp://www.softcircuits.com






- Show quoted text -

So does it mean that data types that don't have a fixed size are
reference types & those having a fixed size are value types?

Thanks,

Ron
 
J

Jonathan Wood

Lars,
No, Strings in Pascal (and ADA as I reacll) are tru types.

This appears to be to me but I don't know what "no" refers to, or what "tru
types" are.

I could be wrong but it seems to me you are confusing terms. I'm not that
familiar with Delphi but a reference in C++ is different from a .NET
reference type. I don't know the exact criteria used to determine value or
reference type, but to me a reference type is a pointer, and so any type
that requires a pointer seems it would be a good candidate. And as far as
I'm concerned, all strings require pointers, whether they are made available
to the language that uses them or not. (Certainly, it wouldn't make sense to
ever store a string in a register or even on the stack.)
Don't know about C# but I hope the compiler takes care of this. By
references or not is not of interest. What is of interest is if you have
the option to use call by value for strings or if all parameters are
treated as references. Can you use call by value in C# how do you use call
by value?

According to http://www.knowdotnet.com/articles/referencetypes2.html, "One
of the most common mistakes developers make when learning .NET is confusing
Reference and Value Types with Passing values by Reference or Value." Again,
I think you are confusing terms.
 
R

RN1

Lars,


This appears to be to me but I don't know what "no" refers to, or what "tru
types" are.

I could be wrong but it seems to me you are confusing terms. I'm not that
familiar with Delphi but a reference in C++ is different from a .NET
reference type. I don't know the exact criteria used to determine value or
reference type, but to me a reference type is a pointer, and so any type
that requires a pointer seems it would be a good candidate. And as far as
I'm concerned, all strings require pointers, whether they are made available
to the language that uses them or not. (Certainly, it wouldn't make sense to
ever store a string in a register or even on the stack.)


According tohttp://www.knowdotnet.com/articles/referencetypes2.html, "One
of the most common mistakes developers make when learning .NET is confusing
Reference and Value Types with Passing values by Reference or Value." Again,
I think you are confusing terms.

OK...now suppose I have the following code:

<script runat="server">
Class MyInt
Public MyValue As Integer
End Class

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim x As New MyInt

...................
...................
...................
End Sub
</script>

If I am not wrong, the Dim line in the Page_Load sub "creates space in
the heap & returns a pointer (say, 0x000001)". To whom does the Dim
line return the pointer?

Please correct me if I am wrong.
 
J

Jonathan Wood

RN1,
OK...now suppose I have the following code:

<script runat="server">
Class MyInt
Public MyValue As Integer
End Class

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim x As New MyInt

...................
...................
...................
End Sub
</script>

If I am not wrong, the Dim line in the Page_Load sub "creates space in
the heap & returns a pointer (say, 0x000001)". To whom does the Dim
line return the pointer?

Please correct me if I am wrong.

Unfortunately, I don't yet know enough about .NET to answer this question
definitively. However, I can tell you that it's entirely possible that the
compiler generates code associated with x that tracks the pointer. Don't
assume there is no pointer just because you don't see it. The compiler does
a great many things behind the scense.

For example, in classic VB, if you declare a String variable a BSTR is
created behind the scenes. This data type involves a pointer. Who would you
say the pointer is returned to in this case?
 
L

Lars

Hi

No means no as in NO (false), then it should be true types. Sorry for my bad
spelling.

A data type of refernese type is not actually a value. It refers to a value.
A value type is actually a real value. A referense refers to or as in C
points to a value. In all programming languages I stumpled except one you
can have two types of parameters. Call by value or cal by referense. In
Basic you use "ByVal" for call by value and "ByRef" (i guess) for call by
referense. The only exception I know is Smalltalk that uses only referenses.
Every data in Smalltalk is dynamicly created.

As for the C++ code I mentioned gets more complicated when you deal with
classes.

See this example in C++ code. Note I'm not a VB programm only used it for a
small program back in 1998.

class TItem
{
private int& item;

// Default constructor
public TItem():
item( *new int; )
{}

// Copy contructor
public TItem( TItem& anInt ):
item( *new int(anInt); )
{}

public ~TItem() { delete *item; }

public int get() { return item; }
public void set( int anItem ) { item = anItem; }
}



// If you didnä't define the copy and default constructors above
// This function would fail to compile since it is call by value.
void aFunction( TItem item )
{
// CODE
}


Now having said this about C++ it is essential to know if all parameters in
C# is treated as referenses or if you can use both cal by value and call by
referense.




"RN1" <[email protected]> skrev i meddelandet
Lars,


This appears to be to me but I don't know what "no" refers to, or what
"tru
types" are.

I could be wrong but it seems to me you are confusing terms. I'm not that
familiar with Delphi but a reference in C++ is different from a .NET
reference type. I don't know the exact criteria used to determine value or
reference type, but to me a reference type is a pointer, and so any type
that requires a pointer seems it would be a good candidate. And as far as
I'm concerned, all strings require pointers, whether they are made
available
to the language that uses them or not. (Certainly, it wouldn't make sense
to
ever store a string in a register or even on the stack.)

ANSI Pascal string at least the old ANSI pascal string type looks as follow

[YXXXXXXXX....XXX]

Where Y is a Byte giving 0..255 as the length of the string. X is caracters
all ANSI strings are arrays. In Delphi which is base on pascal I recall old
ansi Pascal string was replaced with ShortString or some thing. If you use
Delphi 2.0 or later the arrays for the caracters are as you say stored in
array that the string points to. It's been a while sine I dugg into the ANSI
defenitions for C++ but the only string type I know of in C++ is made of
template classes. Old C has no string type at all, hence the need for
pointers to awways.

I do know what call by referense and call by value is. What I don't know
(yet) is if C# can use both as C++ can. To me C# looks reminds me of both VB
and C++.
According tohttp://www.knowdotnet.com/articles/referencetypes2.html, "One
of the most common mistakes developers make when learning .NET is
confusing
Reference and Value Types with Passing values by Reference or Value."
Again,
I think you are confusing terms.

Read the page, good that the authour describes "Deep and Shallow Clones"
what I mentioned as Deep Copy or Shallow Copy. Some thing you learn when
studing basics in Object Oriented Program (OOP) as I did. Thet's when I
learned Smalltalk. If you use Delphi for example evey object of type class
that you pass in the parameter list is in fact a referense. The Deep Copy
versus Shallow copy of objects are not an easy thing to deal with. This can
mess up a lot for you if you don't know. Imagine if you uses a String class
that used Shallow Copy only. Setting

S2 = S1;
S1 = S3;

Would give the result that S1 and S2 had the same value as S3. As I
understand from the page you refered me to C# is doing a Deep Copy. If you
know OOP this should not be that hard to understand. If you don't know about
OOP then you need to study OOP and the problem with Deep Copy versus Shallow
Copy.

Good wuestion about the DIM variable.

In C/C++, Delphi the referense that points to DIM is owned by the functions.
Once you exit the function the reference varialbe dissapears.

The even better question is who owns the pbject you created and where is
that destroid. Does C# come with a garbadge collection like Java, Ada and
Smalltalk. This problem is the main problem OOP using C++ since you have to
destroy the objects you create. What happens when you destroy (delete []
object) and then still have a referense that points (refers) to the deleted
object. (Oooops)


When it comes to data types and algoritms there is really no differense
between a referense and a pointer. Basicly it's the same thing although C++
mess up this for you with the use of pointers. It has to to be backward
compatible with C. The referense types (int&) in C++ is the same as (int&).
The following classes is not the same whenit comes to copy contructors and
default constructors.

class X {
private
int* i;
}

class Y {
private
int& i;
}


X x1(1);
X x2;
Y y1(2);
Y y2

x1=x2; // OK

y1=y2; // Compiler error ,canät generate default and copy condtructors.


What is the similar for this in C#? Can this code be wxecuted i C#?


Lars



OK...now suppose I have the following code:

<script runat="server">
Class MyInt
Public MyValue As Integer
End Class

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim x As New MyInt

...................
...................
...................
End Sub
</script>

If I am not wrong, the Dim line in the Page_Load sub "creates space in
the heap & returns a pointer (say, 0x000001)". To whom does the Dim
line return the pointer?

Please correct me if I am wrong.
 
B

bruce barker

no heap is used.

the variable x is on the stack and is the value, rather than reference
to the value. the variable MyValue being a class static value, is
allocated in the static class definition structure, and again is the
value, not a pointer to the value.

in .net numerics, bools, dates, structures and enums are value types,
everything else is a true object and thus a reference type.

-- bruce (sqlwork.com)
 
L

Lars

bruce barker said:
no heap is used.

the variable x is on the stack and is the value, rather than reference to
the value. the variable MyValue being a class static value, is allocated
in the static class definition structure, and again is the value, not a
pointer to the value.

the answer to the whole issue is very easy

C# Code

// Below is code that profs if nothing else is given in the parameter list
C# uses Call By Value (CBV) "call by value"
//
// Do you really know what CBV and Call By Referense (CBR) means.
// It has nothing to do with how it is stored on stack or heap.
// It has to with how the programmer use the parameters.
//
// CBV makes sure that the function doesn't change the value for the
caller
// weather it's changed within the function or not!
//
// If a function change a value on a CBR parameter the value of the
variable sent as parameter
// is changed for the caller!
//
// This is trivial. This is the same in ALL languages I use except
Smalltalk that only uses CBR.
//
// This code also demonstrates how to use and write default and copy
contructors.
//
// Clicking Buttin1 switches lblY1 and lblY2 and then it set's
lblClassName name to "My String".
// Let's se if any one else knows why, I do but I'll you guess.
//
// Clicking the Button Button2 should increase I, why doesnt it do so?
// Is it because the page is reloaded and the whole object is created
again. .NET programming I guess?
//
// Let's see if I get it right. Change I to a WebControl at it will
increase since WebControls are send back to the server, or?
//
// How ever the default and copy constructors work.
//
using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

namespace Lesson05

{

public partial class LRBand : System.Web.UI.Page

{

String X;

static int I = 0;

public LRBand()

{

setX("My Sting");

}

public LRBand(LRBand anObject)

{

X = anObject.getX();

}

public String getX() { return X; }

public void setX(String anX) { X=anX; }

void swap(String x1, String x2, ref String y1, ref String y2)

{

String tmp;

tmp = x1;

x1 = x2;

x2 = tmp;

tmp = y1;

y1 = y2;

y2 = tmp;


}

protected void Page_Load(object sender, EventArgs e)

{


}

protected void SqlDataSource1_Selected(object sender,
SqlDataSourceStatusEventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

String S1 = lblY1.Text.ToString();

String S2 = lblY2.Text.ToString();

LRBand myClass = new LRBand(this);

swap(lblX1.Text, lblX2.Text, ref S1, ref S2 );

lblY1.Text = S1;

lblY2.Text = S2;

lblClassName.Text = myClass.getX() ;

I += 1;

}

protected void Button2_Click1(object sender, EventArgs e)

{

I = I + I;

lblCount.Text = I.ToString();

}

}

}

//
// lblY1.Text and lblY2.Text switches place. I runthe test on my localhoast
server.
//
// Now if you used your own class that didn't define copy constructors

Lars
 
L

Lars

OPs

I didn't change value since it should be
I = I +1;

not I = I + I;

Late at night I and 1 looks rather a like :O Zzzzzzzzzzzzzzzz

Now does this prof page isn't reloaded as a new page again?

Sorry

Lars
 
M

marss

If I am not mistaken, String is reference type. Can someone please
explain me why is it reference type & not value type?

There is a simple explanation.
All value types in .Net inherently derive from System.ValueType.
System.String does not, it is derived from System.Object. Ambiguity is
mostly caused by immutable nature of String. Any change causes
replacement of an original string, that is why it can't be passed in
procedure by reference.

Regards,
Mykola
http://marss.co.ua - Casual ideas for web development
 
L

Lars

Then the C# String class works as the ANSI string it "should be". Yes there
is an ANSI defenition of a string. Don't know exact how it should be
implemented I know more of how to use it. C++ includes ansi_string in
templates. See Bjarne Strooustrups book The C++ Programming Language. The
best referense book you can get in C++. C# seams to be a big improvement
from C++. And some how like VB going OOP.

One question: When you send an object as a Call By Value parameter and the
paramenter. Doesn it invoke the Copyconstructor and default constructors as
C++ does? This is important to know in case you make you own copy
constructors to do Deep Copy.

Why do you even care if the string is referense typeor value type. You can
use it as both. That's the power of classes OOP default constructors and
copy constructors and of cours ability to write operators like "+".

Another intresting question is if you have a string that includes "aao" or
"<>". In HTML these characters are replaced the later with "&kt;&gt;". When
you check the length of suct string what is the result. How does the String
class handle Chinese letters? If I write "aaoUue" in the IDE in a Label for
example I get the smae characters in the aspx file. Whne doing to in
Dreamvearer it replaces the caracters with the right HTML sequence of
caracters. Is this a bug in VS 2008.

Lars


"marss" <[email protected]> skrev i meddelandet
If I am not mistaken, String is reference type. Can someone please
explain me why is it reference type & not value type?

There is a simple explanation.
All value types in .Net inherently derive from System.ValueType.
System.String does not, it is derived from System.Object. Ambiguity is
mostly caused by immutable nature of String. Any change causes
replacement of an original string, that is why it can't be passed in
procedure by reference.

Regards,
Mykola
http://marss.co.ua - Casual ideas for web development
 
M

marss

One question: When you send an object as a Call By Value parameter
and the paramenter. Doesn it invoke the Copyconstructor and default
constructors as C++ does?

I do not know about VB, but in C# you can't pass an object in a
procedure by value, it is always passed by reference. No copy is
created, no constructor is called.
if you have a string that includes "aao" or "<>". In HTML
these characters are replaced the later with "&kt;&gt;".
When you check the length of suct string what is the result.

There are two different strings with different length (before and
after HTML encoding)
How does the String class handle Chinese letters?

String is an array of Unicode characters. I think 16 bit is quite
enough, even for Chinese symbols.

Regards,
Mykola
http://marss.co.ua - Casual ideas for web development
 
A

Anthony Jones

RN1 said:
OK...now suppose I have the following code:

<script runat="server">
Class MyInt
Public MyValue As Integer
End Class

Sub Page_Load(ByVal obj As Object, ByVal ea As EventArgs)
Dim x As New MyInt

...................
...................
...................
End Sub
</script>

If I am not wrong, the Dim line in the Page_Load sub "creates space in
the heap & returns a pointer (say, 0x000001)". To whom does the Dim
line return the pointer?

Please correct me if I am wrong.

There seems to be some confusion in this thread with lots of references to
other languages and other mis-leading content.

You are correct the MyInt class is allocated off the heap.

The 'pointer' (lets call it a reference shall we) returned by the New
operator is stored in the variable x.

If we did this:-

Dim y As MyInt

y = x

y would also reference the same instance of the MyInt held in heap.

Class types are always stored on the heap, period.

y.MyValue = 16

would result in x.MyValue also being 16 since both variables reference the
same object.


What if we had:-

Structure MyInt
Public MyValue As Integer
Publoc MyOtherValue as Integer
End Structure


In this case the symbol x represents space allocated from the stack to store
the MyInt structure, there is no heap allocation and no reference involved.

y = x

Would result in the content of x being copied to y and this:.

y.MyValue = 16

would not affect the MyValue member held in x.

Note that even single value types like Integer or Double are treated as
Structures.


IMO its better to ask 'Is it a Class or a Structure?' instead of 'Is it a
ValueType or a ReferenceType?' Why? See note 1 after sig, I don't want to
blur things to much here.


So to the original point; is a string a class or a structure? Ans: It's a
class.
Therefore its always allocated in the heap and a variable of string type is
always a reference to this string object allocated on the heap.

Dim x As String = "Hello World"
Dim y As String
y = x

As with all classes in this case y and x both reference the same String
object.

What makes this less obvious (as Mykola alluded to) is the immutable nature
of a String. Once a string object has been allocated and initialised its
content cannot be changed, not even changes that don't involve changing the
length. This results in code which makes strings look like they are
behaving as structures because no where do see an operation on one reference
that is visable through another reference.

A similar type to a string is a character array but a character array is
mutable :-

Dim z As Char() = New Char(2) {"A"c, "B"c, "C"c}
Dim x As Integer()

x = z

x(1) = "X"c

Console.WriteLine(z(1))

Note that both z and x reference the same Array object. A modification made
to the object via one reference is visible using the other. This sort of
operation just isn't available on the string object. Its the lack of this
sort of thing happening in code to a string which gives the illusion of it
being a structure.


However Mykola is in error stating that you can't pass strings as ByRef.
You can (in both VB and C#).

Public Sub DoSomething(ByRef rs As String)
rs = "New content"
End Sub

Dim s as String = "Hello World"

DoSomething(s)

Console.WriteLine(s)


This confusion arises from the overloaded use of the word Reference (which
is why I prefer to think in terms of Structures or Classes). When you
think about it all variables are ultimately references to somewhere in
memory where a value is stored. For example:-

Sub Thing()
Dim i as Integer
Dim o as Object

The symbol i resolves to a offset pointer from the a fixed point on the
stack frame where 4 bytes hold the actual value of the integer. The symbol
o resolves to an offset pointer (likely the same as for i + 4) from the same
fixed point on the stack frame which will hold a reference to some reference
to an object stored on the heap.

Passing ByRef has nothing to do with whether the value is a Structure or a
Class but everything to do with where relative to a fixed point on a stack
frame to find the variable value (be that the actual structure content or
the reference to a heap held object). Since at the time of call the size of
the current frame is known its relatively simple to supply an offset from a
fixed point in the new frame back into the previous.


--
Anthony Jones - MVP ASP/ASP.NET


Note 1:-

A couple of other reasons (apart from my primary reason that the word
reference is already over used) I prefer to think in terms of Structure or
Class instead of ValueType or ReferenceType are:-

1). Its possible to have a reference to a structure. I.e. when its boxed
for example referenced via variable typed as Object.

2.) The MustInherit (abstract) type System.ValueType from which all
'ValueTypes' inherit is a class not a structure. How can a structure inherit
from a Class? Ans: it can't. Only when Boxed does a Structure inherit from
ValueType and at the point its a reference to copy on the heap.

Its all quite confusing.

The terms ValueType and ReferenceType apply globally to an Object (which is
always a reference) and indicates whether the type is 'normally' stored
directly in the variable declared of that type or whether the variable of
that type always holds a reference to the value held on the heap.
 
L

Lars

Hi
So to the original point; is a string a class or a structure? Ans: It's
a
class.
Therefore its always allocated in the heap and a variable of string type
is
always a reference to this string object allocated on the heap.

Dim x As String = "Hello World"
Dim y As String
y = x

As with all classes in this case y and x both reference the same String
object.

Does the String class implements operators to take care of this.

Can you write you own class for example Complex that defines the assignment
operator and comparement operators. Si that if you wrote Z1=Z2 copies the
values Z2.x and Z2.y to Z1 leavind Z2 unchained. Do you have to create a new
object of Z and return for this?
What makes this less obvious (as Mykola alluded to) is the immutable
nature
of a String. Once a string object has been allocated and initialised its
content cannot be changed, not even changes that don't involve changing
the
length. This results in code which makes strings look like they are
behaving as structures because no where do see an operation on one
reference
that is visable through another reference.

A similar type to a string is a character array but a character array is
mutable :-

Dim z As Char() = New Char(2) {"A"c, "B"c, "C"c}
Dim x As Integer()

x = z

x(1) = "X"c

Console.WriteLine(z(1))

Note that both z and x reference the same Array object. A modification
made
to the object via one reference is visible using the other. This sort of
operation just isn't available on the string object. Its the lack of this
sort of thing happening in code to a string which gives the illusion of it
being a structure.


However Mykola is in error stating that you can't pass strings as ByRef.
You can (in both VB and C#).

Public Sub DoSomething(ByRef rs As String)
rs = "New content"
End Sub

Dim s as String = "Hello World"

DoSomething(s)

Console.WriteLine(s)


This confusion arises from the overloaded use of the word Reference (which
is why I prefer to think in terms of Structures or Classes). When you
think about it all variables are ultimately references to somewhere in
memory where a value is stored. For example:-

Sub Thing()
Dim i as Integer
Dim o as Object

The symbol i resolves to a offset pointer from the a fixed point on the
stack frame where 4 bytes hold the actual value of the integer. The
symbol
o resolves to an offset pointer (likely the same as for i + 4) from the
same
fixed point on the stack frame which will hold a reference to some
reference
to an object stored on the heap.

Passing ByRef has nothing to do with whether the value is a Structure or a
Class but everything to do with where relative to a fixed point on a stack
frame to find the variable value (be that the actual structure content or
the reference to a heap held object). Since at the time of call the size
of
the current frame is known its relatively simple to supply an offset from
a
fixed point in the new frame back into the previous.

I Think I got it

public void swap( ref String S1, ref String S2 )
{
String tmp1=S1;
S2=S1;
S1=tmp;
}

What this function does is swapping the reference values. Compare it to the
follwing C++ and Delphi code

public void swap( String&* S1, String&* S2 )
{
String* tmp1=S1;
S2=S1;
S1=tmp;
}

// Delphi code
procedure swap( var String S1, var String S2 )
Strng tmp
begin
tmp = S2;
S1=S2;
S2=tmp;
end;
--
Anthony Jones - MVP ASP/ASP.NET


Note 1:-

A couple of other reasons (apart from my primary reason that the word
reference is already over used) I prefer to think in terms of Structure or
Class instead of ValueType or ReferenceType are:-

When you takea basic course in Datastructures and Algoritms you learn than a
REFERENCE is a reference that refers to another object. Weather it's
implemented by pinters, memory on the heap or any thing else doesn't matter.
A Value is value treated as a value (object). The OBJECT if you prefer.
Every Reference has to refer to an OBJECT. A teacher I had at the Universaty
(Basic Datatypes and Algoritms) told us to look at References is a non
language depandant matter as below. 14 years later I still recall it.


References (pointers for old C programmers, instanses of classes in C#)
{Reference} ----> {Object ( 1,2,3,4,5,6,67,78,)}
or
{Reference} ----> {Object ( 1,2,3,4,5,6,67,78,),Object (
1,2,3,4,5,6,67,78),Object("EHROIERO"}


Objects
{Object ( 1,2,3,4,5,6,67,78,)}
{Object ( 1,2,3,4,5,6,78,)}
{Object ("DJÖLFD","DODHFO")}

1). Its possible to have a reference to a structure. I.e. when its boxed
for example referenced via variable typed as Object.

2.) The MustInherit (abstract) type System.ValueType from which all
'ValueTypes' inherit is a class not a structure. How can a structure
inherit
from a Class? Ans: it can't. Only when Boxed does a Structure inherit
from
ValueType and at the point its a reference to copy on the heap.

For those of you who have hard understanding heap and stack. Look ar the
example above. A pcture says more than a thousand words as they say. If the
object reffered to is on the heap, file, on another server doesn't matter.
Think abstract and you get it.
Its all quite confusing.

Not really wonce you know that all instances of classes are references it's
no problem. What I did was to not only mix C++ and C# I also have a lot of
Delphi code in memmory. In the matter of how to implement instances of
classes Delphi is more like C# than C++ is. In a true Obecj Orienter
Language as Smalltalk every thing is a reference. As I understand C# is move
towards that direction. But C# is not near an truly OBject Oriented
language. Although it you can use OOP techniques. The build in classes oin
C# doesn't support encapsulation fully. For example

// Does LabekX know that you change the value of the Text when I do this?
Does C# allow you to define properties like Delphi.
LabelX.Text = "Some text";

This is important to think of when you wrote your own classes. For every
member (variable) in the class write an accessor and modifier method. In
general Set Get methods. It makes life easy when you inherit the class in
another class.
 
A

Anthony Jones

Lars said:
Hi


Does the String class implements operators to take care of this.

Can you write you own class for example Complex that defines the assignment
operator and comparement operators. Si that if you wrote Z1=Z2 copies the
values Z2.x and Z2.y to Z1 leavind Z2 unchained. Do you have to create a new
object of Z and return for this?

Neither VB nor C# support the overloading of assignment operators or the
concept of a copy constructor.

If your class is simple enough such that all of its fields are structures
(as above) then you can make a copy of class with the inherited
..MemberwiseClone method that comes from object:-

//C#
Z1 = (Complex)Z2.MemberwiseClone()

'VB
Z1 = DirectCast(Z2.MemberwiseClone(), Complex)

For more complex objects where some fields are classes memberwise clone
would not clone the referenced classes. For that you would need to
implement ICloneable and implement the Clone method to perform the Deep copy
and the referenced classes themselves either need to be simple enough that a
memberwiseclone would suffice or also implement ICloneable.

A structure would seem to be a better basis for a complex number. Using a
structure the Z1 = Z2 would by nature create a copy of the member fields.
The mathematical and comparison operators can then be overloaded to provide
the appropriate behaviour.

One thing about parameter passing that might confuse VB6ers is that
Structures can be passed ByVal where they couldn't in VB6. Therefore using
a structure for small composite data structures is actually quite viable in
VB.NET.

An alternative would be to use an immutable class. There are pros and cons
to both approaches.

I Think I got it

public void swap( ref String S1, ref String S2 )
{
String tmp1=S1;
S2=S1;
S1=tmp;
}

Yes that'll work. Not only that but no new string is ever allocated. In VB6
such an operation resulted in 3 string allocation/dealloactions. (Although
hardcore VBers wouldn't do such a swap in this way).
What this function does is swapping the reference values. Compare it to the
follwing C++ and Delphi code

public void swap( String&* S1, String&* S2 )
{
String* tmp1=S1;
S2=S1;
S1=tmp;
}

Yes this is an Identical operation.
When you takea basic course in Datastructures and Algoritms you learn than a
REFERENCE is a reference that refers to another object. Weather it's
implemented by pinters, memory on the heap or any thing else doesn't matter.
A Value is value treated as a value (object). The OBJECT if you prefer.
Every Reference has to refer to an OBJECT. A teacher I had at the Universaty
(Basic Datatypes and Algoritms) told us to look at References is a non
language depandant matter as below. 14 years later I still recall it.

Yeah but I find all the Computer science stuff abstracts things more than
most humans are comfortable with. There are lots of things which can be
considered references but if we kept calling them all 'reference' then we
wouldn't know whch of the various possible 'implementations' of reference
we're talking about.
References (pointers for old C programmers, instanses of classes in C#)
{Reference} ----> {Object ( 1,2,3,4,5,6,67,78,)}
or
{Reference} ----> {Object ( 1,2,3,4,5,6,67,78,),Object (
1,2,3,4,5,6,67,78),Object("EHROIERO"}


Objects
{Object ( 1,2,3,4,5,6,67,78,)}
{Object ( 1,2,3,4,5,6,78,)}
{Object ("DJÖLFD","DODHFO")}



For those of you who have hard understanding heap and stack. Look ar the
example above. A pcture says more than a thousand words as they say. If the
object reffered to is on the heap, file, on another server doesn't matter.
Think abstract and you get it.

Yes there is an abstraction to be had here but whilst abstraction is a good
developers bread and butter its possible to over do it.
Not really wonce you know that all instances of classes are references it's
no problem.

I don't think you are speaking for the majority there though.
What I did was to not only mix C++ and C# I also have a lot of
Delphi code in memmory. In the matter of how to implement instances of
classes Delphi is more like C# than C++ is. In a true Obecj Orienter
Language as Smalltalk every thing is a reference. As I understand C# is move
towards that direction. But C# is not near an truly OBject Oriented
language. Although it you can use OOP techniques. The build in classes oin
C# doesn't support encapsulation fully. For example

// Does LabekX know that you change the value of the Text when I do this?
Does C# allow you to define properties like Delphi.
LabelX.Text = "Some text";

private string myString
string text
{
get { return myString; }
set { myString = value; }
}

I think you might need to read up C#' more before making statements like
'not near a truly object oriented language'. Besides where in the OO book
does it say that a true object supports properties anyway. In fact
properties as singe construct to unify what were otherwise known as Accessor
and Mutator methods is a relatively recent concept in OO languages. I've
even heard C++ zealots slate VB6 for supporting them.
This is important to think of when you wrote your own classes. For every
member (variable) in the class write an accessor and modifier method. In
general Set Get methods. It makes life easy when you inherit the class in
another class.

I certainly agree with this. In fact I would take it further and suggest
that in many cases internal code the is using these private fields should
actually use the property methods instead. This allows overrides of such
members to be used by such code.
 
L

Lars

Hi

Check out the page
http://msdn2.microsoft.com/en-us/library/aa691324(VS.71).aspx

Out take from the page

C# Language Specification
7.2.2 Operator overloading
All unary and binary operators have predefined implementations that are
automatically available in any expression. In addition to the predefined
implementations, user-defined implementations can be introduced by including
operator declarations in classes and structs (Section 10.9). User-defined
operator implementations always take precedence over predefined operator
implementations: Only when no applicable user-defined operator
implementations exist will the predefined operator implementations be
considered.



Does this mean that you can override all operators except assignment =
operator.



Lars
 
A

Anthony Jones

Lars said:
Hi

Check out the page
http://msdn2.microsoft.com/en-us/library/aa691324(VS.71).aspx

Out take from the page

C# Language Specification
7.2.2 Operator overloading
All unary and binary operators have predefined implementations that are
automatically available in any expression. In addition to the predefined
implementations, user-defined implementations can be introduced by including
operator declarations in classes and structs (Section 10.9). User-defined
operator implementations always take precedence over predefined operator
implementations: Only when no applicable user-defined operator
implementations exist will the predefined operator implementations be
considered.



Does this mean that you can override all operators except assignment =
operator.


Try it:-

public class Thing
{
private int x;
private Thing() {}
public Thing(x) { this.x = x}
public static Thing operator = (Thing RHS)
{
return new Thing(x);
}
}

Looks like it ought to work, doesn't compile though. = is not an
overloadable operator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top