473,320 Members | 2,041 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Assigning "this"

Hello, Newsgroupians:

I have a large class with a lot of member variables. I also have a function
in the class that I would like to change ALL Of the member variables. I am
trying to assign "this" to the result, but I always get the error message,
"Cannot assign to '<this>' because it is read-only."

I've been searching on the Internet, and I notice some C# code is violating
this rule. Perhaps their code is wrong.

For simplicity, suppose I have a Point class that two members: x and y.
Suppose I have two functions called DoubleSizes() and Double().
DoubleSizes() is defined as...

public Point DoubleSizes()
{
return new Point(this.x * 2, this.y * 2);
}

Now, for the Double() function, I'd like to have the following...
public Point Double()
{
this = this.DoubleSizes();
return this;
}

But this doesn't work. Instead, I need to set the result to a temporary
variable and iterate through my variables... EXA:

Point temp = this.DoubleSizes();
this.x = temp.x;
this.y = temp.y;

return this;

Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?" Again,
I've seen some C# code changing the value of this, but are they in violation
of a compile rule?

Thank you, all.
Trecius
Oct 16 '07 #1
8 4521
>Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?"
Only inside a constructor of a struct IIRC. Not for classes.
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Oct 16 '07 #2
Mattias Sjögren <ma********************@mvps.orgwrote:
Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?"
Only inside a constructor of a struct IIRC. Not for classes.
You can do it elsewhere in a struct too - but certainly not in classes.

using System;

public class Test
{
struct Foo
{
int y;

public Foo(int x)
{
y = x;
}

public void ChangeTo(int z)
{
this = new Foo(z);
}

public override string ToString()
{
return y.ToString();
}
}

static void Main()
{
Foo f = new Foo(10);
Console.WriteLine(f);
f.ChangeTo(20);
Console.WriteLine(f);
}
}

--
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
Oct 16 '07 #3
Trecius wrote:
Hello, Newsgroupians:

I have a large class with a lot of member variables. I also have a function
in the class that I would like to change ALL Of the member variables. I am
trying to assign "this" to the result, but I always get the error message,
"Cannot assign to '<this>' because it is read-only."

I've been searching on the Internet, and I notice some C# code is violating
this rule. Perhaps their code is wrong.
Or maybe you're misreading the code. Can you provide links to the code
that you believe is wrong?
For simplicity, suppose I have a Point class that two members: x and y.
An unfortunate choice of example, IMHO. .NET already has a Point type,
and it's a struct. Structs are value types and work in a very different
way from classes. This could be confusing in this context.

That said, let's go with your example nevertheless, with the assumption
that we will ignore .NET's Point struct and assume we have a whole new
Point type that is in fact a class...
Suppose I have two functions called DoubleSizes() and Double().
DoubleSizes() is defined as...

public Point DoubleSizes()
{
return new Point(this.x * 2, this.y * 2);
}

Now, for the Double() function, I'd like to have the following...
public Point Double()
{
this = this.DoubleSizes();
return this;
}
First, note that when assigning something to "this", you aren't copying
values from one instance to another. You would be replacing the "this"
reference altogether. Hopefully you can see why, in a class, it doesn't
make sense to try to replace the instance reference from within the
instance itself.

Beyond that, what is the point of the Point.Double() method? In what
situation do you want to modify every member variable of a class while
returning a new instance of the class? Why would you not simply create
a new instance and use that in place of the old one? You can use
something like MemberwiseClone() to create an exact value-for-value
duplicate of a class, if you're looking for getting two different
instances (for example, you want to modify one without changing the other).
But this doesn't work. Instead, I need to set the result to a temporary
variable and iterate through my variables... EXA:

Point temp = this.DoubleSizes();
this.x = temp.x;
this.y = temp.y;

return this;
Yes, if you want the original instance to be the same instance after the
operation, you will have to modify each and every member variable
individually. But IMHO this is suggestive of a more basic design issue.
If your design is such that you feel you want to replace the class
from within based on an operation that returns a different, new
instance, I would suggest there's a problem with the design itself.
Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?" Again,
I've seen some C# code changing the value of this, but are they in violation
of a compile rule?
Again, if you could post links to the examples of code you say does
this, that would be helpful. I think it's likely the code isn't doing
what you think it's doing.

In addition, it would be helpful if you could try to clarify what it is
exactly you're trying to do. The code you're posting doesn't fit
exactly with the words you're writing. In particular, you seem to just
want to copy values from one instance to another, but the code you've
posted isn't doing that (even if the compiler let you). It's replacing
the instance reference altogether.

Do you want to replace the reference? If so, how would you expect that
to work? If not, then why are you trying to write code that would (if
it compiled) replace the reference? Are you confused about the
difference between a struct and a class?

Pete
Oct 16 '07 #4
Perhaps the OP is searching for the Smalltalk "become" operation, wherein
A.become(B) would swap all references to A with a reference to B, and
vice-versa. There is no such function in C# (or in the CLR, so far as I
know), although it would not be too hard to implement. See
http://blade.nagaokaut.ac.jp/cgi-bin...by-talk/104551.

The semantics might be problematic in C# unless A and B were of the same
class. Owing to Smalltalk's runtime type checking this is not a problem
(but of limited utility, admittedly, when the objects are of different
classes).

"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:13*************@corp.supernews.com...
Trecius wrote:
>Hello, Newsgroupians:

I have a large class with a lot of member variables. I also have a
function in the class that I would like to change ALL Of the member
variables. I am trying to assign "this" to the result, but I always get
the error message, "Cannot assign to '<this>' because it is read-only."

I've been searching on the Internet, and I notice some C# code is
violating this rule. Perhaps their code is wrong.

Or maybe you're misreading the code. Can you provide links to the code
that you believe is wrong?
>For simplicity, suppose I have a Point class that two members: x and y.

An unfortunate choice of example, IMHO. .NET already has a Point type,
and it's a struct. Structs are value types and work in a very different
way from classes. This could be confusing in this context.

That said, let's go with your example nevertheless, with the assumption
that we will ignore .NET's Point struct and assume we have a whole new
Point type that is in fact a class...
>Suppose I have two functions called DoubleSizes() and Double().
DoubleSizes() is defined as...

public Point DoubleSizes()
{
return new Point(this.x * 2, this.y * 2);
}

Now, for the Double() function, I'd like to have the following...
public Point Double()
{
this = this.DoubleSizes();
return this;
}

First, note that when assigning something to "this", you aren't copying
values from one instance to another. You would be replacing the "this"
reference altogether. Hopefully you can see why, in a class, it doesn't
make sense to try to replace the instance reference from within the
instance itself.

Beyond that, what is the point of the Point.Double() method? In what
situation do you want to modify every member variable of a class while
returning a new instance of the class? Why would you not simply create a
new instance and use that in place of the old one? You can use something
like MemberwiseClone() to create an exact value-for-value duplicate of a
class, if you're looking for getting two different instances (for example,
you want to modify one without changing the other).
>But this doesn't work. Instead, I need to set the result to a temporary
variable and iterate through my variables... EXA:

Point temp = this.DoubleSizes();
this.x = temp.x;
this.y = temp.y;

return this;

Yes, if you want the original instance to be the same instance after the
operation, you will have to modify each and every member variable
individually. But IMHO this is suggestive of a more basic design issue.
If your design is such that you feel you want to replace the class from
within based on an operation that returns a different, new instance, I
would suggest there's a problem with the design itself.
>Again, this is a small example. In my case, I have about twenty
variables that I'd like to reassign. Is it just possible to reassign
"this?" Again, I've seen some C# code changing the value of this, but
are they in violation of a compile rule?

Again, if you could post links to the examples of code you say does this,
that would be helpful. I think it's likely the code isn't doing what you
think it's doing.

In addition, it would be helpful if you could try to clarify what it is
exactly you're trying to do. The code you're posting doesn't fit exactly
with the words you're writing. In particular, you seem to just want to
copy values from one instance to another, but the code you've posted isn't
doing that (even if the compiler let you). It's replacing the instance
reference altogether.

Do you want to replace the reference? If so, how would you expect that to
work? If not, then why are you trying to write code that would (if it
compiled) replace the reference? Are you confused about the difference
between a struct and a class?

Pete

Oct 16 '07 #5
Fred Mellender wrote:
Perhaps the OP is searching for the Smalltalk "become" operation, wherein
A.become(B) would swap all references to A with a reference to B, and
vice-versa.
Vice-a-versa? As in all references to B also are replaced with
references to A?

Anyway, perhaps that's what the OP wants, but if so they (one hopes)
have a higher-level design issue that they are trying to address with
that behavior.

Since C# doesn't allow assignment to the "this" of a class, they aren't
going to get the specific behavior. So the only remaining question is
really what probably are they really trying to solve? Then answers can
be provided more along the lines of what C# actually does provide.

Pete
Oct 16 '07 #6
Thank you, Mr. Sjogren and Mr. Skeet, for a quick response.

Also, thank you to Mr. Mellender and Mr. Duniho for alternative approach to
my predicament.

Thank you, all, again.
Trecius

"Trecius" wrote:
Hello, Newsgroupians:

I have a large class with a lot of member variables. I also have a function
in the class that I would like to change ALL Of the member variables. I am
trying to assign "this" to the result, but I always get the error message,
"Cannot assign to '<this>' because it is read-only."

I've been searching on the Internet, and I notice some C# code is violating
this rule. Perhaps their code is wrong.

For simplicity, suppose I have a Point class that two members: x and y.
Suppose I have two functions called DoubleSizes() and Double().
DoubleSizes() is defined as...

public Point DoubleSizes()
{
return new Point(this.x * 2, this.y * 2);
}

Now, for the Double() function, I'd like to have the following...
public Point Double()
{
this = this.DoubleSizes();
return this;
}

But this doesn't work. Instead, I need to set the result to a temporary
variable and iterate through my variables... EXA:

Point temp = this.DoubleSizes();
this.x = temp.x;
this.y = temp.y;

return this;

Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?" Again,
I've seen some C# code changing the value of this, but are they in violation
of a compile rule?

Thank you, all.
Trecius
Oct 16 '07 #7

Define a private inner-class to hold all of your private fields (I
hope you don't have any public fields!) and then in your constructor
create an instance of this private class and then use that for all
private field access.

Then in the situation where you need to assign everything, you can do
it by assigning the private class.

public class Point {
private class PointData {
public int x;
public int y;
}

private PointData data = new PointData();

public int X {
get { return data.x; }
set { data.x = value; }
}

public int Y {
get { return data.y; }
set { data.y = value; }
}

public void Become(Point other) {
data = other.data;
}
}

Note that this is a reference assignment so it can have unintended
side-effects (depends on what your intended behavior, you can do a
clone instead of assignment).

It's not exactly the same implementation but it's similar to Memento
design pattern. http://www.dofactory.com/Patterns/PatternMemento.aspx

HTH,

Sam
------------------------------------------------------------
We're hiring! B-Line Medical is seeking .NET
Developers for exciting positions in medical product
development in MD/DC. Work with a variety of technologies
in a relaxed team environment. See ads on Dice.com.
On Tue, 16 Oct 2007 10:57:00 -0700, Trecius
<Tr*****@discussions.microsoft.comwrote:
>Hello, Newsgroupians:

I have a large class with a lot of member variables. I also have a function
in the class that I would like to change ALL Of the member variables. I am
trying to assign "this" to the result, but I always get the error message,
"Cannot assign to '<this>' because it is read-only."

I've been searching on the Internet, and I notice some C# code is violating
this rule. Perhaps their code is wrong.

For simplicity, suppose I have a Point class that two members: x and y.
Suppose I have two functions called DoubleSizes() and Double().
DoubleSizes() is defined as...

public Point DoubleSizes()
{
return new Point(this.x * 2, this.y * 2);
}

Now, for the Double() function, I'd like to have the following...
public Point Double()
{
this = this.DoubleSizes();
return this;
}

But this doesn't work. Instead, I need to set the result to a temporary
variable and iterate through my variables... EXA:

Point temp = this.DoubleSizes();
this.x = temp.x;
this.y = temp.y;

return this;

Again, this is a small example. In my case, I have about twenty variables
that I'd like to reassign. Is it just possible to reassign "this?" Again,
I've seen some C# code changing the value of this, but are they in violation
of a compile rule?

Thank you, all.
Trecius
Oct 16 '07 #8
Samuel R. Neff wrote:
[...]
Note that this is a reference assignment so it can have unintended
side-effects (depends on what your intended behavior, you can do a
clone instead of assignment).
If those side-effects are not desired, an alternative to using a clone
of the class would be to simply define a struct to contain the data
instead, so that each instance of the class has its own copy of the data
implicitly.

Pete
Oct 16 '07 #9

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

Similar topics

5
by: Michael Stevens | last post by:
Probably the wrong wording but since I'm not a scripter I won't claim to know what I'm talking about. I got this script from www.htmlgoodies.com <script language="JavaScript"> <!--...
3
by: Hodad | last post by:
I would like to adapt, as much as possible, the appearance and color red of the font in this button: <P><CENTER><BUTTON VALUE="SUBMIT"><A...
1
by: Peter King | last post by:
if you assign multiple classes in order to keep your classes generic e.g ..classA { position.absolute; left:5 top:5 height:200 width:800 } ..classB { background-color: red} ..classC {...
3
by: maadhuu | last post by:
well,i am curious to know what would be the output of the following: delete this; basically , comment on this .
1
by: tnhoe | last post by:
Hi, <Form method='post' action="next.htm?btn="+"this.myform.myobj.value"> What is the correct syntax for above ? Regards Hoe
1
by: Shapper | last post by:
Hello, I am accessing a value in a XML value: news.Load(Server.MapPath("xml/ news.rss")) newslabel.Text = CType(news.SelectSingleNode("rss version=&quot;2.0 &quot;/channel/title").InnerText, String) ...
7
by: relient | last post by:
Question: Why can't you access a private inherited field from a base class in a derived class? I have a *theory* of how this works, of which, I'm not completely sure of but makes logical sense to...
10
by: craig.keightley | last post by:
I am trying to get the next row within a loop for a script i am developing... I need to display a final table row within the table that i have displayed on the page, but i only want to show it...
3
mrjohn
by: mrjohn | last post by:
Hullo, I've been learning C# and I had a question. I'm creating a class, and I was writing the constructor. When I was assigning values to it's variables, I found that the compiler seems to take it...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.