473,698 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using property to reference Struct data

I don't understand why I cannot use a property to modify data within a
struct. Can someone tell me why I get the error "Cannot modify the return
value of "myData.TheData " because it is not a variable.

Here is what breaks.

struct Data
{
public Data(){}
private int someData;
public int TheData
{
get { return someData; }
set { someData = value; }
}
}

class Sample
{
Data myData = new Data();

void AMethod()
{
myData.TheData = 7;
}
}

If I don't use the property "TheData" and instead make "int someData" public
I can reference myData.someData = 7 and it will work just fine. Why can't a
property be used?

--
-----------
Thanks,
Steve
Feb 7 '06 #1
14 3274
The property construct is fine.

I'm wondering why you declared a default constructor for a struct,
though, since C# doesn't allow them. Try removing the constructor and
see if it works.

Feb 7 '06 #2
This isn't the code that gave you that warning. This code fails to
compile with the error, "Structs cannot have parameterless
constructor." Please post the exact code that gave you the error.

Feb 7 '06 #3
Adding the constructor was my mistake. I don't have it in the actual code.

A MS help comment says:

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.
I therefore created a temp value and assigned my structure to it. The only
thing is that when updating the temp reference it didn't update my structure.

Data tmp = myData;
tmp.TheData = 7;

This assigned 7 to TheData in the tmp value, but it didn't update the myData
"data". I can't figure out way.

myData is part of a static global structure. Could the static nature have
anything to do with it?
--
-----------
Thanks,
Steve
"dotnetchic " wrote:
The property construct is fine.

I'm wondering why you declared a default constructor for a struct,
though, since C# doesn't allow them. Try removing the constructor and
see if it works.

Feb 7 '06 #4
I copied your code in to a VS2003 project, removed the spurious
constructor, and it compiles with no warnings or errors.

Please post the exact code that caused this compiler error. I suspect I
know what's going on, but I can't say until I see the real code.

Feb 7 '06 #5
Here is my code, I trimmed out the stuff that wasn't necessary.

Create a project called TestSamples with a form that does nothing for now.
Simple insert this code and it will compile with the error I indicated. If
you change "public struct TimeDelayEventD ata" to "public class
TimeDelayEventD ata" then it works just fine.

This code is my "GlobalData class"

using System;
using System.Collecti ons;

namespace TestSamples
{
/// <summary>
/// Summary description for Class1.
/// </summary>
internal class GlobalData
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit .
static GlobalData() {}
/// <summary>
/// Default constructor
/// </summary>
private GlobalData()
{
// Set up the global data structures
this.timeDelayD ata = new TimeDelayEventD ata();

// Set up event handlers for the time delay events
this.timeDelayR equestor = new TimeDelayReques tEvents();
this.timeDelayL istener = new TimeDelayFullfi llEvents();
this.timeDelayL istener.AddEven t(this.timeDela yRequestor);
}

/// <summary>
/// Create a static instance of this class.
/// </summary>
static readonly GlobalData instance = new GlobalData();
/// <summary>
/// References the data regarding the time delays for the testing
/// </summary>
private TimeDelayEventD ata timeDelayData;
/// <summary>
/// Reference to the event handler to fulfill the event of passing
time delay data to the global data structure
/// </summary>
private TimeDelayFullfi llEvents timeDelayListen er;
/// <summary>
/// Reference to the event handler to request time delay events
/// </summary>
private TimeDelayReques tEvents timeDelayReques tor;

/// <summary>
/// Get a reference to this instance of this class.
/// </summary>
public static GlobalData Instance
{
get { return GlobalData.inst ance; }
}

/// <summary>
/// Get a reference to the time delay data.
/// </summary>
public TimeDelayEventD ata MyTimeDelayData
{
get
{
return this.timeDelayD ata;
}
}

/// <summary>
/// Get a reference to the time delay requestor
/// </summary>
public TimeDelayReques tEvents MyTimeDelayRequ estor
{
get
{
return this.timeDelayR equestor;
}
}
}
}
Here is my TimeDelayEventD ata struct...

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace TestSamples
{
public struct TimeDelayEventD ata
{
/// <summary>
/// Ignore the date when asked to run the test
/// </summary>
private bool ignoreDate;
/// <summary>
/// This enum identifies the data that is to be updated
/// </summary>
private TimeDelayIdenti fiers timeDelayIdenti fier;

/// <summary>
/// Get or set the flag indicating that the date should be ignored
when asked to run the test
/// </summary>
public bool IgnoreDate
{
get
{
return ignoreDate;
}
set
{
ignoreDate = value;
}
}
/// <summary>
/// Get or set the identifier that identifies the data to be updated
in the event
/// </summary>
public TimeDelayIdenti fiers Identifier
{
get
{
return timeDelayIdenti fier;
}
set
{
timeDelayIdenti fier = value;
}
}
}
}

Here is my event handler classes...

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace TestSamples
{
/// <param name="hourData" >This structure identifies and contains the
data to be sent to the event</param>
public delegate void TimeDelayEventH andler(TimeDela yEventData data);

public class TimeDelayReques tEvents
{
/// <summary>
/// This event requests an update to the hour data.
/// </summary>
public event TestSamples.Tim eDelayEventHand ler
timeDelayUpdate RequestEvent;

/// <summary>
/// Default constructor
/// </summary>
public TimeDelayReques tEvents()
{
}

/// <summary>
/// Issue the request to update the hour data.
/// </summary>
/// <param name="obj">Time Delay data to be updated when an event
occurs</param>
private void RequestUpdateEv ent(TimeDelayEv entData obj)
{
if (timeDelayUpdat eRequestEvent != null)
timeDelayUpdate RequestEvent(ob j);
}

/// <summary>
/// Make the request to update the data being passed for time delay
information.
/// </summary>
/// <param name="obj">Time Delay data to be udpated when an event
occurs</param>
public void OnUpdate(TimeDe layEventData obj)
{
RequestUpdateEv ent(obj);
}
}

/// <summary>
/// This class handles all fullfillments requests for updating the
global data representing the time delay data.
/// </summary>
public class TimeDelayFullfi llEvents
{
/// <summary>
/// References the request to handle a time delay event
/// </summary>
private TimeDelayReques tEvents requestEvent = null;
/// <summary>
/// Default constructor
/// </summary>
public TimeDelayFullfi llEvents()
{
}

/// <summary>
/// Remove any previous event instance.
/// </summary>
protected void RemoveEvent()
{
if (this.requestEv ent != null)
this.requestEve nt.timeDelayUpd ateRequestEvent -= new
TimeDelayEventH andler(this.Upd ateTimeDelayDat a);
}

/// <summary>
/// Update the data for the time delay information
/// </summary>
private void UpdateTimeDelay Data(TimeDelayE ventData data)
{
switch (data.Identifie r)
{
case TimeDelayIdenti fiers.IgnoreDat e:
GlobalData.Inst ance.MyTimeDela yData.IgnoreDat e =
data.IgnoreDate ;
break;
}
}

/// <summary>
/// Add the event handler for the time delay events
/// </summary>
/// <param name="request"> Requesting event to update the time delay
data</param>
public void AddEvent(TimeDe layRequestEvent s request)
{
// Remove any instances of an old request.
this.RemoveEven t();

// Create the new handler.
this.requestEve nt = request;
this.requestEve nt.timeDelayUpd ateRequestEvent +=new
TimeDelayEventH andler(this.Upd ateTimeDelayDat a);
}
}
}
Here is my TimeDelayIdenti fiers...

using System;
using System.Collecti ons.Generic;
using System.Text;

namespace TestSamples
{
/// <summary>
/// This enum is used to identify which data in the event is to be updated
/// </summary>
public enum TimeDelayIdenti fiers
{
/// <summary>
/// Indicates the data is in the ignoreDate field
/// </summary>
IgnoreDate = 1,
}
}

--
-----------
Thanks,
Steve
"Bruce Wood" wrote:
I copied your code in to a VS2003 project, removed the spurious
constructor, and it compiles with no warnings or errors.

Please post the exact code that caused this compiler error. I suspect I
know what's going on, but I can't say until I see the real code.

Feb 7 '06 #6
I presume that you have a class that has, as one of its members, a
variable of a structure type and that you are trying to do something
like this:

ClassVariable.S tructure.Struct ureProperty = 1;

You are getting the error because when you call ClassVariable.S tructure
you are getting a *copy* of the structure and not a reference to the
actual structure. So any changes you make to *copy* will not be copied
to the structure in the class.

You need to do something like this:

//Get the copy of the structure and save in a variable
MyStruct tmp = ClassVariable.S tructure;

//Modify the copy
tmp.StructurePr operty = 1;

//Replace the structure in the class instance with the copy.
ClassVariable.S tructure = tmp;

Or, instead of a structure, use a class then you wont have to create a
tmp copy since you will be working with references.

Feb 7 '06 #7
And the line that causes the compiler error is:

GlobalData.Inst ance.MyTimeDela yData.IgnoreDat e = data.IgnoreDate ;

in class TimeDelayFullfi llEvents. Right?

Remember that structs have _value semantics_. That means that when you
say: GlobalData.Inst ance.MyTimeDela yData, you are getting a _copy_ of
the TimeDelayData within the GlobalData object, not a _reference_ to
the TimeDelayData.

So, when you say MyTimeDelayData .IgnoreDate = ... what you're saying
is, "Return me a copy of the TimeDelayData from the GlobalData object,
then make a change to that copy, then throw it away." Throw it away
because you don't store the copy anywhere, so the compiler chucks it.

Mutable structs are strange beasts and tricky to work with. Unless
you're going to be creating and destroying millions (and I do mean
_millions_) of these things, you're better off making it a class, not a
struct. Then it will act in a more reasonable manner. The other
possibility is to make it immutable (no sets in any of your struct's
properties), which forces you to create a "new" one and assign it to
the property, rather than trying to set _its_ properties.

Feb 7 '06 #8
With your explanation and Bruce's this has clarified for me my mistake.
Thanks to you both.
--
-----------
Thanks,
Steve
"Chris Dunaway" wrote:
I presume that you have a class that has, as one of its members, a
variable of a structure type and that you are trying to do something
like this:

ClassVariable.S tructure.Struct ureProperty = 1;

You are getting the error because when you call ClassVariable.S tructure
you are getting a *copy* of the structure and not a reference to the
actual structure. So any changes you make to *copy* will not be copied
to the structure in the class.

You need to do something like this:

//Get the copy of the structure and save in a variable
MyStruct tmp = ClassVariable.S tructure;

//Modify the copy
tmp.StructurePr operty = 1;

//Replace the structure in the class instance with the copy.
ClassVariable.S tructure = tmp;

Or, instead of a structure, use a class then you wont have to create a
tmp copy since you will be working with references.

Feb 7 '06 #9
This explanation has clarified for me my mistake. Thank you for you time.
I'll use it as a class.

Would you mind looking at my post "An Event Listener" posted today? Maybe
you can help me there as well.

--
-----------
Thanks,
Steve
"Bruce Wood" wrote:
And the line that causes the compiler error is:

GlobalData.Inst ance.MyTimeDela yData.IgnoreDat e = data.IgnoreDate ;

in class TimeDelayFullfi llEvents. Right?

Remember that structs have _value semantics_. That means that when you
say: GlobalData.Inst ance.MyTimeDela yData, you are getting a _copy_ of
the TimeDelayData within the GlobalData object, not a _reference_ to
the TimeDelayData.

So, when you say MyTimeDelayData .IgnoreDate = ... what you're saying
is, "Return me a copy of the TimeDelayData from the GlobalData object,
then make a change to that copy, then throw it away." Throw it away
because you don't store the copy anywhere, so the compiler chucks it.

Mutable structs are strange beasts and tricky to work with. Unless
you're going to be creating and destroying millions (and I do mean
_millions_) of these things, you're better off making it a class, not a
struct. Then it will act in a more reasonable manner. The other
possibility is to make it immutable (no sets in any of your struct's
properties), which forces you to create a "new" one and assign it to
the property, rather than trying to set _its_ properties.

Feb 7 '06 #10

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

Similar topics

11
6593
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
9
3966
by: Guy | last post by:
I have extended the datetimepicker control to incorporate a ReadOnly property. I have used the new keyword to implement my own version of the value property, so that if readonly == true then it will not set the value of the control and will leave the checked status of the checkbox to false when a user selects a new date. this works fine when using the control on a win2k machine but if we use it on a win XP box and call
7
1883
by: _ed_ | last post by:
I'd like to build a class or struct composed of pointers to variables. Does this require dropping into an 'unsafe' block, or is there a trick? .... int value1 = 1234; bool value2 = false; string value3 = "Hello Detroit"; public class x {
11
2015
by: Nemanja Trifunovic | last post by:
A question for C# language experts: If I have a struct that implements IDisposable: struct C : IDisposable { public int clan; public void Dispose() { Console.WriteLine("Disposing");
0
3935
by: Lokkju | last post by:
I am pretty much lost here - I am trying to create a managed c++ wrapper for this dll, so that I can use it from c#/vb.net, however, it does not conform to any standard style of coding I have seen. It is almost like it is trying to implement it's own COM interfaces... below is the header, and a link to the dll+code: Zip file with header, example, and DLL:...
6
1394
by: JSheble | last post by:
Are there any reasons why I shouldn't or couldn't use a structure as a property in a class? Specifically since structures are value types and objects are reference types? I have a Shipping object that has 4 different types of addresses. Initially, I created 4 instances of an Address object, but seem inefficient to me since the Address itslef doesn't really have (or need) and methods... I was thinking a structure would be more...
9
2389
by: Bill Grigg | last post by:
All, Can anyone supply an example or reference to an example of using reflection to determine the data types and array lengths contained in a nested stucture in C#? Actually, it is a structure that I use to communicate to some unmanaged code in a DLL written in C. It is not complicated, but will change and I would like to be able to sequentially access it without explicitly referring to each and every element. Here is the structure:
53
4662
by: Hexman | last post by:
Hello All, I'd like your comments on the code below. The sub does exactly what I want it to do but I don't feel that it is solid as all. It seems like I'm using some VB6 code, .Net2003 code, and .Net2005 code. I'm developing in vb.net 2005. This test sub just reads an input text file, writing out records to another text file, eliminating records that have a '99' in them (it is similar to a CSV file). Some of my concerns are:
45
18872
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies of their elements? Why can't I change the element itself? class Program { private struct MyStruct
0
8673
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
8601
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
9021
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...
0
8860
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7716
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...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4365
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
4614
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
1998
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.