473,387 Members | 1,891 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,387 software developers and data experts.

Assigning a reference to a variable

Jon
If I have a structure, for example:

struct Settings{
public string str;
public double doub1, doub2;
public int i1;
}

How do I assign the reference of i1 to a variable? I can easily do this by passing it as a ref int
to a function, but is there a way to do this without passing it to a function?
Nov 26 '07 #1
20 5170
On Nov 26, 4:44 pm, "Jon" <.wrote:
If I have a structure, for example:

struct Settings{
public string str;
public double doub1, doub2;
public int i1;

}

How do I assign the reference of i1 to a variable? I can easily do this by passing it as a ref int
to a function, but is there a way to do this without passing it to a function?
No. If you want a type to behave like a reference type, you should
make it a reference type to start with.

Jon
Nov 26 '07 #2
Jon wrote:
If I have a structure, for example:

struct Settings{
public string str;
public double doub1, doub2;
public int i1;
}

How do I assign the reference of i1 to a variable? I can easily do this by passing it as a ref int
to a function, but is there a way to do this without passing it to a function?
You can do it using unsafe code, but I wouldn't recommend that. If you
use unsafe code, the syntax is very similar to C++.

Settings sets = new Settings();
sets.i1 = 5;
int *x = &sets.i1;
*x = 6;

Console.WriteLine(sets.i1.ToString());
--
Tom Porterfield
Nov 26 '07 #3
Jon
Thanks for your replies Jon + Tom.

I'm from a C background, but I don't really want to use unsafe code.

"If you want a type to behave like a reference type, you should make it a reference type to start
with." How do I make an integer a reference type?

Jon
"Jon" <.wrote in message news:Oq*************@TK2MSFTNGP06.phx.gbl...
If I have a structure, for example:

struct Settings{
public string str;
public double doub1, doub2;
public int i1;
}

How do I assign the reference of i1 to a variable? I can easily do this by passing it as a ref int
to a function, but is there a way to do this without passing it to a function?

Nov 27 '07 #4
"If you want a type to behave like a reference type, you should make it a reference type to start
with." How do I make an integer a reference type?
You don't; you make Settings a reference type by changing "struct" to
"class". It is normally *very* rare to write a "struct" in .net, and
usually relates to discreet (but possibly compound) "values" - such as
a CompexInt32 or TimeRange.
How do I assign the reference of i1 to a variable?
There is no such thing as a reference of i1; you could "box" it, but
that changes the meaning.
I can easily do this by passing it as a ref int
Actually, this does something different again... can I recommend you
read the following? (one of Jon's pages)

http://www.pobox.com/~skeet/csharp/parameters.html

Marc
Nov 27 '07 #5
Jon
Thanks Marc. I read Jon Skeet's page a few weeks ago and found it very helpful.

I think my problem is that my mind thinks in C, and it's having some problems adapting to C#.

I'm a bit nervous about changing the structs (I have quite a few) to classes, since it might break
something.

Am I right in saying that I can get a reference to an array inside a struct? If so, would having a
single-element array work?

struct Settings{
public string str;
public double doub1, doub2;
public intRef[];
}

....

int[] int1 = new int[1];
intRef = int1;

"Marc Gravell" <ma**********@gmail.comwrote in message
news:a8**********************************@f3g2000h sg.googlegroups.com...
"If you want a type to behave like a reference type, you should make it a reference type to start
with." How do I make an integer a reference type?
You don't; you make Settings a reference type by changing "struct" to
"class". It is normally *very* rare to write a "struct" in .net, and
usually relates to discreet (but possibly compound) "values" - such as
a CompexInt32 or TimeRange.
How do I assign the reference of i1 to a variable?
There is no such thing as a reference of i1; you could "box" it, but
that changes the meaning.
I can easily do this by passing it as a ref int
Actually, this does something different again... can I recommend you
read the following? (one of Jon's pages)

http://www.pobox.com/~skeet/csharp/parameters.html

Marc
Nov 27 '07 #6
On 2007-11-27 01:20:14 -0800, "Jon" <.said:
[...]
I'm a bit nervous about changing the structs (I have quite a few) to
classes, since it might break something.
Like what?

IMHO, on the balance it's more likely that switching to classes will
_fix_ more things than it breaks. :)
Am I right in saying that I can get a reference to an array inside a
struct? If so, would having a single-element array work?
Yes. But boy, what a hack.

It's hard to offer specific advice without specific information
regarding what you're trying to do here. But my general rule of thumb
is: if you find yourself hacking around a perceived limitation in the
language, your first thought should be that you simply haven't adapted
to the language yet and your time would be better-spent figuring out
what the language-friendly way to solve your design issue is.

It's not a perfect rule of thumb, but it's served me very well over the years.

You haven't explained in any detail why it is you want to be able to
pass an integer variable by reference, but it's likely that whatever
the reason, you're just going to make things hard on yourself later by
not learning and accepting the normal way of doing things in C# now.

Pete

Nov 27 '07 #7
Hi Jon,

Do you mind to tell me why you want to assign an integer reference to
another variable? What is the type of the another variable? Yes, in .Net
any array is reference type, however, I do not think your
solution/workaround is neat and may cause some other problems.

If you tell us the reason for the requirement, there may be a better
solution for it. Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 28 '07 #8

"Marc Gravell" <ma**********@gmail.comwrote in message
news:a8**********************************@f3g2000h sg.googlegroups.com...
>"If you want a type to behave like a reference type, you should make it a
reference type to start
with." How do I make an integer a reference type?

You don't; you make Settings a reference type by changing "struct" to
"class". It is normally *very* rare to write a "struct" in .net, and
usually relates to discreet (but possibly compound) "values" - such as
a CompexInt32 or TimeRange.
That's interesting. As a beginner, I haven't really used structs much at
all - just a couple for the purposes of seeing what they do. I haven't used
them more, because I couldn't actually see any benefit of structs over
classes (except possibly a microscopic performance gain). I have felt guilty
about this, as I am not using what appeared to be a major part of the
language.

Are you now telling me that I needn't feel guilty about pretty much ignoring
struct types?

Nov 28 '07 #9
On 2007-11-27 18:53:25 -0800, "Peter Webb"
<we********@DIESPAMDIEoptusnet.com.ausaid:
That's interesting. As a beginner, I haven't really used structs much
at all - just a couple for the purposes of seeing what they do. I
haven't used them more, because I couldn't actually see any benefit of
structs over classes (except possibly a microscopic performance gain).
I have felt guilty about this, as I am not using what appeared to be a
major part of the language.

Are you now telling me that I needn't feel guilty about pretty much
ignoring struct types?
That's right. :)

Actually, there are real benefits to using a struct in certain
situations. They can perform better in some cases. For example, when
you have a lot of them and can allocate an array to contain the
collection (e.g. an actual Array, or some generic collection that uses
an array to store the values).

Of course, being a value type, they can also reduce performance if used
inappropriately. And they have subtly different semantics than
reference types, which can result in hard-to-identify bugs (especially
if the structs are mutable).

I would say that in the long run, you'll probably want to at least
spend some time learning about structs, how they are different from
classes, and why you might use them. Even if you never use a struct,
you'll at least understand better why you're not using them. Also,
since a lot of what makes a struct different from a class is the same
as what makes any value type different from a class, understanding
structs will help you understand the other value types as well.

Pete

Nov 28 '07 #10
Jon
Hi Jeffrey,

Thanks for offering to help.

I have a variable that I would like to use as a reference to different variables within my struct.

My original example struct was too generalised to show this, and although the following is a
simplification of my real code, it is closer to a concise but complete example...
struct Settings{
public int left, right, centre;
}

Settings set = new Settings();
int ref intRef ; // ILLEGAL C# STATEMENT - note the use of "ref"
if(???) intRef = set.left;
else if(???) intRef = set.right;
else intRef = set.centre;

Then I would change the value that intRef points to.
From my C perspective, If I can do this with an array, it seems reasonable to me that I should be
allowed to do it with an int. I cannot do anything dangerous (eg increment a pointer which might
then point to something invalid).

To repliers who have suggested using a class rather than a struct, I'm not sure if this would
actually with my example, but maybe you can advise on this.

Jon
""Jeffrey Tan[MSFT]"" <je***@online.microsoft.comwrote in message
news:LQ**************@TK2MSFTNGHUB02.phx.gbl...
Hi Jon,

Do you mind to tell me why you want to assign an integer reference to
another variable? What is the type of the another variable? Yes, in .Net
any array is reference type, however, I do not think your
solution/workaround is neat and may cause some other problems.

If you tell us the reason for the requirement, there may be a better
solution for it. Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
Nov 28 '07 #11
On Nov 28, 2:53 am, "Peter Webb"
<webbfam...@DIESPAMDIEoptusnet.com.auwrote:
That's interesting. As a beginner, I haven't really used structs much at
all - just a couple for the purposes of seeing what they do. I haven't used
them more, because I couldn't actually see any benefit of structs over
classes (except possibly a microscopic performance gain).
It's not really about performance gain, usually - it's about reference
type semantics vs value type semantics.
I have felt guilty
about this, as I am not using what appeared to be a major part of the
language.

Are you now telling me that I needn't feel guilty about pretty much ignoring
struct types?
Well, you're not *really* ignoring structs - you're just not creating
your *own* struct types.
Whenever you use int, Guid, long, float, byte etc you're using
structs.

It's a bit like generics - many people will never need to write their
own generic type or generic method (although I'd argue there's often a
lot of benefit for doing so) - but they may well *use* the existing
generic collections.

Jon
Nov 28 '07 #12
Jon
Hi Peter

"Like what?" I don't actually know - I'm following the "if it ain't broke, don't fix it" philosophy
at the moment. I'm curious about your comment that switching to classes will fix more things than it
breaks. Are structs really that delicate?

"Yes. But boy, what a hack." I agree.

"you simply haven't adapted to the language yet and your time would be better-spent figuring out
what the language-friendly way to solve your design issue is" I agree - see the extra details I've
given in my reply to Jeffrey's question.

Thanks for you help,

Jon
"Peter Duniho" <Np*********@NnOwSlPiAnMk.comwrote in message
news:2007112701514843658-NpOeStPeAdM@NnOwSlPiAnMkcom...
On 2007-11-27 01:20:14 -0800, "Jon" <.said:
[...]
I'm a bit nervous about changing the structs (I have quite a few) to
classes, since it might break something.
Like what?

IMHO, on the balance it's more likely that switching to classes will
_fix_ more things than it breaks. :)
Am I right in saying that I can get a reference to an array inside a
struct? If so, would having a single-element array work?
Yes. But boy, what a hack.

It's hard to offer specific advice without specific information
regarding what you're trying to do here. But my general rule of thumb
is: if you find yourself hacking around a perceived limitation in the
language, your first thought should be that you simply haven't adapted
to the language yet and your time would be better-spent figuring out
what the language-friendly way to solve your design issue is.

It's not a perfect rule of thumb, but it's served me very well over the years.

You haven't explained in any detail why it is you want to be able to
pass an integer variable by reference, but it's likely that whatever
the reason, you're just going to make things hard on yourself later by
not learning and accepting the normal way of doing things in C# now.

Pete
Nov 28 '07 #13
On 2007-11-28 03:16:33 -0800, "Jon" <.said:
Hi Peter

"Like what?" I don't actually know - I'm following the "if it ain't
broke, don't fix it" philosophy at the moment. I'm curious about your
comment that switching to classes will fix more things than it breaks.
Are structs really that delicate?
It's not so much that they are delicate, but that they are in some ways
significantly different from classes, even as they look very similar.
For a person just learning C#, it's possible that just as you find
yourself getting comfortable with the "reference-only" nature of
classes (something that's necessary for effective C# programming),
something specific about the value-type nature of structs will be
overlooked, resulting in a confusing bug.

This can especially problematic for someone experienced in C++
programming, where there's no real difference between a struct and a
class except for default accessibility. In C#, structs and classes
fill very specific roles, different from each other.

I didn't mean to give the impression that structs are somehow a fragile
way to code. They aren't. It's just that they a different enough from
classes that it's not hard to get confused about how to use them,
especially for someone new to the language (and I'm not just saying
this in an abstract way...I was once new to the language myself, and I
still remember the process of figuring out the implications of the
difference between a value type and a reference type).

Pete

Nov 28 '07 #14
On 2007-11-29 00:40:14 -0800, "Jon" <.said:
Thanks for your reply again Peter. *intRef will be used many times at
various points, so a
simplified example is...
Okay. I'll take you at your word that this is necessary. You should
consider the possibility that the overall design could be improved.
But, assuming you really need to write the code that way, one possible
alternative would be to use an anonymous method:

delegate type declared somewhere:

delegate void SetField(int valueNew);
then in a method somewhere:

Settings set = new Settings();
SetField setter;

if (???)
setter = delegate(int valueNew) { set.left = valueNew; };
else if (???)
setter = delegate(int valueNew) { set.right = valueNew; };
else
setter = delegate(int valueNew) { set.centre = valueNew; };

setter(...);

Some general code

setter(...);

Some general code

setter(...);

etc...

Actually, I should learn more about lamba expressions. I suspect that
the syntax would be nicer with one. I wonder if you could even get
away without having to declare the delegate type using a lamba
expression. Maybe someone more knowledgeable will comment. In the
meantime, the above should work.

Pete

Nov 29 '07 #15
lamba expressions. I suspect that
the syntax would be nicer with one.
I'll comment on the lambda syntax, but I'm undecided whether this is a
good use case:

Action<intsetter;
....
setter = newValue =set.left = newValue;

However - perhaps the bigger concern here is the impact of "captured
variables"; you might have to be very careful; not enough info to
assess if this is a problem.
I wonder if you could even get away without having to declare the delegate type
using a lamba expression.
Not really (unless it is obvious and "var"), but it would be "in
vogue" to use Action<inthere.

Marc
Nov 29 '07 #16
Hi Jon,

Thanks for your feedback.

I think Peter has provided very good discussion and suggestion to you.
Below is some other comment:

From another perspective, I do not think using a general intRef
pointer/reference for different purpose and different places is a best
practise. It would make the code review and Refactor a bit harder. For
example, it is hard for the reviewer to understand the logic meaning of
intRef variable in a big function. So it may be good to assgin these int
variables directly without using a intRef variable as indirection. However,
I agree that this may not be a big problem. Just a thought for
consideration. Thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 30 '07 #17
Hi Jon,

Have you reviewed all the replies to you? Do they make sense to you? If you
still need any help, please feel free to feedback, thanks.

Best regards,
Jeffrey Tan
Microsoft Online Community Support

Dec 4 '07 #18
Jon
Thanks once again for the replies and advice. I been doing some non-software work for two weeks, and
am now returning to the problem.

I've decided to restructure things and to send the value within the struct to a function

if(???) func(ref set.left, ...);
else if(???) func(ref set.right, ...);
else func(ref set.centre, ...);

Jon
Dec 13 '07 #19

"Jon" <.wrote in message news:Od**************@TK2MSFTNGP05.phx.gbl...
Thanks once again for the replies and advice. I been doing some
non-software work for two weeks, and
am now returning to the problem.

I've decided to restructure things and to send the value within the
struct to a function

if(???) func(ref set.left, ...);
else if(???) func(ref set.right, ...);
else func(ref set.centre, ...);
I know that you received solid advice that makes for a cleaner design,
for instance, using classes and delegates.

Why do you persist in this approach.
If your brain still thinks in C instead of C#, it's time to get a new
brain.

Dec 14 '07 #20
Jon
Someone mentioned changing the struct to a class, but when I gave more details of my problem (reply
to Peter Doniho dated 29 November 2007 08:40 - I'm from the UK, so time may be different elsewhere)
no one mentioned classes again. I don't see how changing to a class would help.

Delegates: Peter Doniho suggested this (reply dated 29 November 2007 18:02). I considered this, but
by re-arranging things and putting more into a function, it looked cleaner to me.

"Bill Butler" <qw****@asdf.comwrote in message news:2uv8j.20519$k22.16734@trnddc02...

"Jon" <.wrote in message news:Od**************@TK2MSFTNGP05.phx.gbl...
Thanks once again for the replies and advice. I been doing some
non-software work for two weeks, and
am now returning to the problem.

I've decided to restructure things and to send the value within the
struct to a function

if(???) func(ref set.left, ...);
else if(???) func(ref set.right, ...);
else func(ref set.centre, ...);
I know that you received solid advice that makes for a cleaner design,
for instance, using classes and delegates.

Why do you persist in this approach.
If your brain still thinks in C instead of C#, it's time to get a new
brain.


Dec 17 '07 #21

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

Similar topics

5
by: Dave | last post by:
Hello all, Please consider the code below. It is representative of a problem I am having. foo_t needs to contain a bar_t which is a class without a copy constructor or operator=. It is not...
37
by: Dave | last post by:
Hello all, Please consider the code below. It is representative of a problem I am having. foo_t needs to contain a bar_t which is a class without a copy constructor or operator=. It is not...
6
by: adamrfrench | last post by:
Let it be mentioned that Javascript is not my forte, so the solution to this could very well be a simple one. I am working on an AJAX function where I can pass a URL and the target ID in, and...
20
by: weston | last post by:
I've got a piece of code where, for all the world, it looks like this fails in IE 6: hometab = document.getElementById('hometab'); but this succeeds: hometabemt =...
2
by: eBob.com | last post by:
I know that this must be a really dumb question but I just can't find an answer. I want to associate some information with a RichTextBox. The Tag property seems to be the intended way to "hang"...
25
by: Sourav | last post by:
Suppose I have a code like this, #include <stdio.h> int *p; void foo(int); int main(void){ foo(3); printf("%p %d\n",p,*p);
7
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written...
3
by: Donos | last post by:
Hello I have the following program, void getValue(unsigned char* pVal) { pVal = allValues(); } unsigned char* allValues()
8
by: =?Utf-8?B?VHJlY2l1cw==?= | last post by:
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...
10
by: flopbucket | last post by:
Hi, Is this legal? std::string foo() { std::string xyz = "FOO"; return xyz; }
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.