473,657 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

my rant on value types and accessors

I am really unhappy that C# accessors are not powerful
enough to mimic as if you were accessing an class field.

In particular, let S be:

public struct S {
public int v;
public void change () { v = 99; }
}

Let C be:

public class C {
public S s;
}

Then I could change the value of s, by soing:

C c;
c.s.change ();

If, instead, I wanted to run access to s through an accessor:

public class C {
private S s;
public S s_accessor {
get { return s; }
set { s = value; }
}
}

Then the expression:

C c;
c.s_accessor.ch ange ();

will not have the same effect as:

C c;
c.s.change ();

I find this to be a big flaw. I.e. accessors cannot mimic the behavior
of
value typed fields properly. I also think this flaw is unfixable, b/c
Microsoft
itself exhibits this flaw in its own implementation of Nullable types:

class Test {

public struct S {
public int v;
public void ch () { v = 88; }
}

public static void Main () {
S y;
y.v = 0;
S? x = y;
x.Value.ch ();

Console.WriteLi ne ("{0}", x.Value.v);
}
}

Prints out "0", instead of the naturally expected "88".

Jun 15 '06 #1
3 1348
The Petar wrote:
Prints out "0", instead of the naturally expected "88".

In other words, you want S to reference sematics instead of value
sematic. So, then, why are you make it a struct instead of a class?

Jun 15 '06 #2
<ja**********@g mail.com> wrote in message
news:11******** *************@p 79g2000cwp.goog legroups.com...
The Petar wrote:
Prints out "0", instead of the naturally expected "88".

In other words, you want S to reference sematics instead of value
sematic. So, then, why are you make it a struct instead of a class?


I don't know, maybe to allocate an array of 1000 of them as local variables
without hammering the garbage collector. Maybe because 99% of the time the
type is used with value semantics, and calling Clone() all the time is just
too much (and again hammers the garbage collector). Maybe it's predefined
as a struct in someone else's class library. In short, a million reasons.

For example, how about having a Vector class:

class Vector
{
private Point internalHead;
public Point Head
{
get { return internalHead; }
set { internalHead = value; }
}

//same for tail
}

System.Drawing. Point is a struct. Microsoft already made that choice. But
now you can do (where v is type Vector):
int x = v.Head.X;
but not
v.Head.X = x*3; // changes temporary Point returned from get_Head()

In the good old days of C++, there was no difference between struct and
class. Reference and value semantics were both available for all
user-defined types using language features such as "references ".

MyStruct operator[](int index) const; // value semantics
MyStruct& operator[](int index); // reference semantics

Actually this has been true from ordinary C, but in C you had to use
pointers, which required the caller to use a different syntax, and
encouraged breaking type-safety. C# is a throwback to C...

The answer is: yes you can get reference semantics with structs. You must
use pointers to do so. You use the -> operator familiar to C/C++
programmers for accessing structure members through a pointer. And you must
mark your code as "unsafe"... though the documentation suggests unsafe is
only needed if you do pointer arithmetic. I haven't tested whether you can
do:
int a = 5;
int* p = &a;
p->ToString();
without an unsafe context. There's no pointer arithmetic, so type-safety is
assured.

However, you're going to have a problem when you need a pointer to a struct
inside a ref class, because the garbage collector can change the object.
What you really need is the fancy support Microsoft added to C++/CLI to
handle all of this very neatly: tracking references (%) and interior_ptr.

If C# let you override operator->, you could have interior_ptr in C# pretty
quick. Instead, you need to have member (so they can access the private
fields backing the public properties) classes or structs, with properties
defined so that they proxy the properties of the private field.

class Vector
{
private Point internalHead;
public class RefHeadPoint
{
private Point? fromPoint;
private Vector boss;
public RefHeadPoint(Po int pt) : fromPoint(pt), boss(null) {}
public RefHeadPoint(Ve ctor v) : fromPoint(null) , boss(v) {}
public static implicit operator Point(RefHeadPo int pt) { return
pt.pt ?? pt.boss.interna lHead; }
public static implicit operator RefHeadPoint(pt ) { return new
RefHeadPoint(pt ); }
public int X
{
get { return (pt ?? boss.internalHe ad).X; }
set { if (pt.HasValue) pt.X = value; else boss.internalHe ad.X =
value; }
}
// same for Y
}

public RefHeadPoint Head
{
get { return new RefHeadPoint(th is); }
set { internalHead = (Point)value; }
}

//same for tail
}

and now you can write:
v.Head.X = x*3;
Jun 15 '06 #3
"Ben Voigt" <rb*@nospam.nos pam> wrote in message
news:em******** ******@TK2MSFTN GP04.phx.gbl...

In the good old days of C++, there was no difference between struct and
class.


Right -- so some folks wondered why they had both class and struct. The
answer, of course, was that an OOP language must have classes! :)

///ark
Jun 15 '06 #4

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

Similar topics

2
1708
by: Nick Patavalis | last post by:
Why does the following print "0 0" instead of "0 1"? What is the canonical way to rewrite it in order to get what I obviously expect? class C(object): __val = 0 def set_value(self, val): if val < 0 : self.__val = 0 else : self.__val = val def get_value(self): return self.__val
0
1234
by: Jarma | last post by:
Taking such a piece of code: template<class T> class Data { public: Data(T v) : value(v) {} T GetValue1() const { return value; } const T & GetValue2() const { return value; }
8
17298
by: Matt Herson | last post by:
I have been trying to find a way to use JavaScript to change the value of a hidden field on submit. I am already invoking a JavaScript to handle the validation on submit. The reason I need to change this field is some of the forms have two buttons on them, each needs to process the form differently. If I can change the value of the hidden field dynamically it will solve my issue as I can run each against a diffent cgi. Currently my...
0
1101
by: gao_bolin | last post by:
I have a library that has a class Signal<T> whose data type is templated. The class comes with a whole bunch of functions and objects to do various processing on the signal. What I would like to do is a DSignal class that does essentially the same thing, but whose type is unknown at compile type. Since I have already this template library with everything I want in it, I would like to maximally reuse it and minimize overheads. It's the...
9
2923
by: ckerns | last post by:
I want to loop thru an array of controls,(39 of them...defaults = 0). If value is null or non-numeric I want to assign the value of "0". rowString = "L411" //conrol name if (isNaN(eval ("document.forms."+rowString+".value")) == true ) { //this alert works if the value is a letter,i.e,"a" alert("You have entered an non-numeric value.\nEnter a number in the appropriate box.");
2
1653
by: John Wood | last post by:
I'm just considering embarking on writing a class that does a better job than the Serialize attribute. The serialize attribute is no good because it sucks at even the most basic of versioning. So the idea is to write something that uses reflection and a simple persistable named/value pairs object (using BinaryWriter) to store the state of the object graph. I'd rather not write it though... other than writing custom serialization, what...
8
3025
by: Jason | last post by:
In the c++ debugger I could give it a memory address of some data and it would break when that data changed. It is very helpful when you have a single value change of a large amount of code and you just want to know what/where/why its changing. I tried to hook it up like I in C++, opening up the new break point window, going to the data tab and supplying a pointer... just for fun I put in the var name ( since there are no pointers in c# )...
8
1365
by: yo_mismo | last post by:
Hi, I send a parameter from a Form (Form1) to an other form (Form2): Form2 frm2 = new Form2(); frm2.number_frm2 = number_frm1; frm2.Show(); The problem i got is that the variable 'number_frm2' always have the value 0 (it's an integer). I have declared it as 'public' but i can't get the right
112
13804
by: mystilleef | last post by:
Hello, What is the Pythonic way of implementing getters and setters. I've heard people say the use of accessors is not Pythonic. But why? And what is the alternative? I refrain from using them because they smell "Javaish." But now my code base is expanding and I'm beginning to appreciate the wisdom behind them. I welcome example code and illustrations.
0
8413
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
8842
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...
1
8513
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,...
1
6176
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
4173
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
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2742
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
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
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.