By P a u l

2009-11-17 09:39:46 8 Comments

I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable?

public Point Origin { get; set; }

Origin.X = 10; // fails with CS1612

Error Message: Cannot modify the return value of 'expression' because it is not a variable

An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.

To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.


@Mitselplik 2019-01-15 16:27:13

Aside from debating the pros and cons of structs versus classes, I tend to look at the goal and approach the problem from that perspective.

That being said, if you don't need to write code behind the property get and set methods (as in your example), then would it not be easier to simply declare the Origin as a field of the class rather than a property? I should think this would allow you to accomplish your goal.

struct Point
    public int X { get; set; }
    public int Y { get; set; }

class MyClass
    public Point Origin;

MyClass c = new MyClass();
c.Origin.X = 23;   // No error.  Sets X just fine

@nawfal 2013-04-25 07:48:48

By now you already know what the source of the error is. In case a constructor doesn't exist with an overload to take your property (in this case X), you can use the object initializer (which will do all the magic behind the scenes). Not that you need not make your structs immutable, but just giving additional info:

struct Point
    public int X { get; set; }
    public int Y { get; set; }

class MyClass
    public Point Origin { get; set; }

MyClass c = new MyClass();
c.Origin.X = 23; //fails.

//but you could do:
c.Origin = new Point { X = 23, Y = c.Origin.Y }; //though you are invoking default constructor

//instead of
c.Origin = new Point(23, c.Origin.Y); //in case there is no constructor like this.

This is possible because behind the scenes this happens:

Point tmp = new Point();
tmp.X = 23;
tmp.Y = Origin.Y;
c.Origin = tmp;

This looks like a very odd thing to do, not at all recommended. Just listing an alternate way. The better way to do is make struct immutable and provide a proper constructor.

@supercat 2013-04-25 15:38:29

Wouldn't that trash out the value of Origin.Y? Given a property of type Point, I would think the idiomatic way to change just X would be var temp=thing.Origin; temp.X = 23; thing.Origin = temp;. The idiomatic approach has the advantage that it doesn't have to mention the members it doesn't want to modify, a feature which is only possible because Point is mutable. I'm puzzled at the philosophy that says that because the compiler can't allow Origin.X = 23; one should design a struct to require code like Origin.X = new Point(23, Origin.Y);. The latter seems really icky to me.

@nawfal 2013-04-25 16:41:20

@supercat oh yes, overlooked that! I will edit it

@nawfal 2013-04-25 16:57:51

@supercat this is the first time I'm thinking of your point, makes a lot of sense! Do you have an alternate pattern/design idea to tackle this? It would have been easier had C# not provided the default constructor for a struct by default (in that case I strictly have to pass both X and Y to specific constructor). Now it loses the point when one can do Point p = new Point(). I know why its really required for a struct, so no point in thinking abt it. But do you have a cool idea to update just one property like X?

@supercat 2013-04-25 17:10:05

For structs which encapsualate a collection of independent but related variables (such as coordinates of a point), my preference is to simply have the struct expose all its members as public fields; to modify one member of a struct property, simply read it out, modify the member, and write it back. It would have been nice if C# had provided a "simple Plain-Old-Data-Struct" declaration which would automatically define a constructor whose parameter list matched the field list, but the people responsible for C# despise mutable structs.

@nawfal 2013-04-25 18:37:13

@supercat I get it. The inconsistent behaviour of structs and classes is confusing.

@supercat 2013-04-25 18:57:13

The confusion results from the IMHO unhelpful belief that everything should behave like a class object. While it's useful to have a means of passing value-type values to things that expect heap object references, it's not useful to pretend value-type variables hold things which derive from Object. They don't. Every value-type definition actually defines two kinds of things: a storage location type (used for variables, array slots, etc.) and a heap object type, sometimes referred to as a "boxed" type (used when a value-type value is stored to a reference-type location).

@supercat 2013-04-25 19:04:45

If one says object o = 5;, the o will hold a reference to an instance of heap-object type System.Int32, which derives from System.Object. If, however, one instead says int i = 5;, then i will hold the bit pattern 0000...00000101. If one regards value types as existing in their own "universe" distinct from heap object types, their behavior will make sense. If one pretends that they're derivatives of System.Object, however, it won't. I suggest adopting the world-view which matches the way things actually behave.

@nawfal 2013-04-25 19:08:58

@supercat I understand the conceptual difference between the two, but again thanks for explanation. My original comment was a musing than any questioning..

@AnthonyWJones 2009-11-17 09:47:33

Using a backing variable won't help. The Point type is a Value type.

You need to assign the whole Point value to the Origin property:-

Origin = new Point(10, Origin.Y);

The problem is that when you access the Origin property what is returned by the get is a copy of the Point structure in the Origin properties auto-created field. Hence your modification of the X field this copy would not affect the underlying field. The compiler detects this and gives you an error since this operation is entirely useless.

Even if you used your own backing variable your get would look like:-

get { return myOrigin; }

You'd still be returning a copy of the Point structure and you'd get the same error.

Hmm... having read your question more carefully perhaps you actually mean to modify the backing variable directly from within your class:-

myOrigin.X = 10;

Yes that would be what you would need.

@MSIL 2009-11-17 09:52:48

I guess the catch here is that you are trying to assign object's sub-values in the statement rather than assigning the object itself. You need to assign the entire Point object in this case as the property type is Point.

Point newOrigin = new Point(10, 10);
Origin = newOrigin;

Hope I made sense there

@Hans Kesting 2009-11-17 14:21:40

The important point is that Point is a struct (valuetype). If it was a class (object) then the original code would have worked.

@MSIL 2009-11-18 04:08:59

Correctamundo - This can be a good interview question.

@supercat 2013-04-25 18:49:33

@HansKesting: If Point were a mutable class type, the original code would have set field or property X in the object returned by property Origin. I see no reason to believe that would have the desired effect upon the object containing the Origin property. Some Framework classes have properties that copy their state to new mutable class instances and return those. Such a design has the advantage of allowing code like thing1.Origin = thing2.Origin; to set the state of object's origin to match that of another, but it can't warn about code like thing1.Origin.X += 4;.

@Fredrik Normén 2009-11-17 09:54:45

The problem is that you point to a value located on the stack and the value will not be relfected back to the orignal property so C# does not allow you to return a reference to a value type. I think you can solve this by removing the Origin property and instead use a public filed, yes I know it's not a nice solution. The other solution is to not use the Point, and instead create your own Point type as an object.

@Greg Beech 2009-11-17 15:33:02

If the Point is a member of a reference type then it will not be on the stack, it will be on the heap in the containing object's memory.

@Greg Beech 2009-11-17 09:49:02

This is because Point is a value type (struct).

Because of this, when you access the Origin property you're accessing a copy of the value held by the class, not the value itself as you would with a reference type (class), so if you set the X property on it then you're setting the property on the copy and then discarding it, leaving the original value unchanged. This probably isn't what you intended, which is why the compiler is warning you about it.

If you want to change just the X value, you need to do something like this:

Origin = new Point(10, Origin.Y);

@Doug 2014-06-27 15:26:19

@Paul: Do you have the ability to change the struct to a class?

@Alexander 2017-05-01 21:50:02

This is kind of a bummer, because the property setter im assigning has a side effect (the struct acts as a view into a backing reference type)

@Artorias2718 2017-11-10 00:02:05

Another solution is to simply make your struct into a class. Unlike in C++, where a class and a struct differ only by the default member access (private and public, respectively), structs and classes in C# have a few more differences. Here's some more info:…

Related Questions

Sponsored Content

22 Answered Questions

[SOLVED] How do you give a C# Auto-Property a default value?

63 Answered Questions

[SOLVED] What is the difference between String and string in C#?

27 Answered Questions

[SOLVED] Get int value from enum in C#

  • 2009-06-03 06:46:39
  • jim
  • 1350142 View
  • 1632 Score
  • 27 Answer
  • Tags:   c# enums casting int

26 Answered Questions

[SOLVED] Cast int to enum in C#

  • 2008-08-27 03:58:21
  • lomaxx
  • 1220694 View
  • 2920 Score
  • 26 Answer
  • Tags:   c# enums casting

26 Answered Questions

[SOLVED] How do I enumerate an enum in C#?

10 Answered Questions

[SOLVED] What are the correct version numbers for C#?

63 Answered Questions

[SOLVED] How do I calculate someone's age in C#?

  • 2008-07-31 23:40:59
  • Jeff Atwood
  • 553350 View
  • 1742 Score
  • 63 Answer
  • Tags:   c# .net datetime

8 Answered Questions

[SOLVED] How to loop through all enum values in C#?

296 Answered Questions

[SOLVED] Hidden Features of C#?

  • 2008-08-12 16:32:24
  • Serhat Ozgel
  • 669945 View
  • 1475 Score
  • 296 Answer
  • Tags:   c# hidden-features

5 Answered Questions

[SOLVED] Is there a reason for C#'s reuse of the variable in a foreach?

Sponsored Content