473,326 Members | 2,680 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,326 software developers and data experts.

method ref to arbitrary value type instance

It seems that in C#, given an instance "a" of some value type "A", one can pass a by reference to functions with signatures of either "void f(object obj)" or "void g(ref A obj)". But passing a into a function with signature "void f(ref object obj)" gives a compile error -- why

(This is part of solving the original problem posed here: http://www.csharp-station.com/ShowPost.aspx?PostID=3625 What I need now is a method that accepts a ref to an arbitrary value type instance, or some other approach to the original problem. Ideas would be welcome.

% cat u.c
using System

struct A
public A(int x, int y) { d_x = x; d_y = y;
public override string ToString(
{ return String.Format("({0},{1})", d_x, d_y);
/
int d_x, d_y
class RefTest

static void f(object obj
{ Console.WriteLine("f: obj={0}", obj);

static void g(ref A obj
{ Console.WriteLine("g: obj={0}", obj);

static void h(ref object obj
{ Console.WriteLine("h: obj={0}", obj);

static void i(ref System.ValueType obj
{ Console.WriteLine("i: obj={0}", obj);

static void Main(

A a = new A(3,2)

f(a)

g(ref a)

// h(ref a)
// u.cs(33,5): error CS1502: The best overloaded method match for 'RefTest.h(ref object)' has some invalid argument
// u.cs(33,11): error CS1503: Argument '1': cannot convert from 'ref A' to 'ref object

// i(ref a)
// u.cs(37,5): error CS1502: The best overloaded method match for 'RefTest.i(ref System.ValueType)' has some invalid argument
// u.cs(37,11): error CS1503: Argument '1': cannot convert from 'ref A' to 'ref System.ValueType


Jul 21 '05 #1
9 2038
Andrew <an*******@discussions.microsoft.com> wrote:
It seems that in C#, given an instance "a" of some value type "A", one
can pass a by reference to functions with signatures of either "void
f(object obj)" or "void g(ref A obj)". But passing a into a function
with signature "void f(ref object obj)" gives a compile error -- why?


The type for a parameter which is passed by reference has to be exactly
the same as the type of the actual parameter. Leave boxing out of the
picture here, and let's use string as an example. Suppose I have a
string variable x, and a method which takes "ref object obj" as a
formal parameter. You might think it would be okay to pass "ref x" as
the actual parameter... but what if the code for the method being
called was:

void Foo (ref object obj)
{
obj = new object();
}

Suddenly you have a string variable which contains a reference to a
non-string object!

Instead, you need to do:

object tmp = x;
Foo (ref tmp);

and then if you're really confident that tmp will still be a string
afterwards you can do:

x = (string) tmp;

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information about pass-by-reference and pass-by-value semantics.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #2
I see

It does seem a bit peculiar though that there is only one way to get a reference to a value instance (by making a method that accepts a ref to a value instance of a specific type), and that way does not allow a way to get a reference to an arbitrary value type instance. Maybe the ability to do that would lead to trouble too.
Jul 21 '05 #3
Andrew <an*******@discussions.microsoft.com> wrote:
I see.

It does seem a bit peculiar though that there is only one way to get a
reference to a value instance (by making a method that accepts a ref
to a value instance of a specific type), and that way does not allow a
way to get a reference to an arbitrary value type instance. Maybe the
ability to do that would lead to trouble too.


You need to be very clear about the difference between *a* reference
and passing a parameter *by* reference.

If you want to pass an arbitrary value type *by* reference, you could
do:

int x = 5;
ValueType v = x;
Foo (ref v);
x = (int) v;
Foo (ref ValueType v)
{
....
}

Again though - if Foo actually is implemented as something like:

v = 't';

then the cast will fail...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #4
> You need to be very clear about the difference between *a* reference
and passing a parameter *by* reference


Was I not clear about this

Jul 21 '05 #5
Andrew <an*******@discussions.microsoft.com> wrote:
You need to be very clear about the difference between *a* reference
and passing a parameter *by* reference.


Was I not clear about this?


No. For instance:

<quote>
It does seem a bit peculiar though that there is only one way to get a
reference to a value instance (by making a method that accepts a ref to
a value instance of a specific type), and that way does not allow a way
to get a reference to an arbitrary value type instance.
</quote>

"Reference" when used as a noun in .NET is specifically a reference to
null or an object on the heap. Passing a value type parameter by
reference *doesn't* do that - boxing does, effectively. That's the kind
of care over terminology I'm encouraging. I know it sounds horribly
pedantic, but I think it makes discussions much more useful.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #6
In that paragraph I was using the term "reference" in the general computer science sense. I hope this clarifies things for you

Andrew
Jul 21 '05 #7
Andrew <an*******@discussions.microsoft.com> wrote:
In that paragraph I was using the term "reference" in the general
computer science sense. I hope this clarifies things for you.


Yes, I thought you probably were - and while that's all very well, it
confuses things when talking in a .NET forum. I find it's easier to
move a .NET discussion forward when talking in *purely* .NET terms
wherever possible.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #8
I can appreciate wanting people to use what you think is standard terminology. Of course, one way to drive people away from a domain is to complain about their use of perfectly reasonable but outside-domain terminology while not answering their question. And it's just not reasonable to expect that people are going to frame their discussion in exactly the terminology you want. What would be better is to point out what you think are imprecisions, when helping along the main discussion

What happens when someone just talks about the terminology, and not the main question, is unfortunate and inevitable. In this thread, and in another thread I started last fall, you ended up sidetracking the discussion to the point where there is virtually no chance of anyone replying to the followup question that I asked. That is not helpful

I mention this in the spirit of trying to get you to think about this next time. The first response you wrote was helpful to me; the other ones have been anti-helpful because they sidetracked the discussion. Now, people get to read us going back and forth about something they could care less about, and possibly they get to read me writing the same question in another thread, if I want an answer.
Jul 21 '05 #9
Andrew <an*******@discussions.microsoft.com> wrote:
I can appreciate wanting people to use what you think is standard
terminology. Of course, one way to drive people away from a domain is
to complain about their use of perfectly reasonable but outside-domain
terminology while not answering their question. And it's just not
reasonable to expect that people are going to frame their discussion
in exactly the terminology you want. What would be better is to point
out what you think are imprecisions, when helping along the main
discussion.
I was trying to help answer the question at the same time, but it's
difficult to exactly answer the question when you don't necessarily
know exactly what the question is due to incorrect terminology, which
is part of my point.

While it's not necessarily reasonable to expect people to *initially*
frame theirs question in correct terminology, I don't think it's
unreasonable to ask people to *reframe* their questions in correct
terminology in order to help them better, having also helped them to
understand the correct terminology. It's not like I just say, "Your
terminology is wrong, go away."
What happens when someone just talks about the terminology, and not
the main question, is unfortunate and inevitable. In this thread, and
in another thread I started last fall, you ended up sidetracking the
discussion to the point where there is virtually no chance of anyone
replying to the followup question that I asked. That is not helpful.
I pretty much always try to include an answer to the question, while
trying to clarify *exactly* what is meant by the question in the first
place. I don't know which other thread you mean, unfortunately, so I
can't speak for that. Apologies if I didn't answer your question
though. I really do try to.
I mention this in the spirit of trying to get you to think about this
next time. The first response you wrote was helpful to me; the other
ones have been anti-helpful because they sidetracked the discussion.
Even in my second response I was talking about your question, wasn't I?
After that I thought your original question had been answered, and the
posts were only about terminology.
Now, people get to read us going back and forth about something they
could care less about, and possibly they get to read me writing the
same question in another thread, if I want an answer.


Do you think there is actually more to the answer than I've already
given? I've shown why you can't pass an arbitrary unboxed value type by
reference. (I should also mention that you can't pass an arbitrary
unboxed value type by value either, as the stack needs to know the size
of the argument in advance.) I've shown how you can work around that
with boxing, if you're confident that you know the type after the
method call. What more do you need to know?

This discussion is probably best continued by email - feel free to mail
me with a reply. (I'd have sent this by email if I could have done.)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #10

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

Similar topics

12
by: Donnal Walter | last post by:
The following method is defined in one of my classes: def setup(self, items={}): """perform setup based on a dictionary of items""" if 'something' in items: value = items # now do something...
24
by: ALI-R | last post by:
Hi All, First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0) Ok,Let's see: I was reading an article that When...
18
by: JohnR | last post by:
From reading the documentation, this should be a relatively easy thing. I have an arraylist of custom class instances which I want to search with an"indexof" where I'm passing an instance if the...
44
by: gregory.petrosyan | last post by:
Hello everybody! I have little problem: class A: def __init__(self, n): self.data = n def f(self, x = ????) print x All I want is to make self.data the default argument for self.f(). (I
9
by: Andrew | last post by:
It seems that in C#, given an instance "a" of some value type "A", one can pass a by reference to functions with signatures of either "void f(object obj)" or "void g(ref A obj)". But passing a into...
19
by: zzw8206262001 | last post by:
Hi,I find a way to make javescript more like c++ or pyhon There is the sample code: function Father(self) //every contructor may have "self" argument { self=self?self:this; ...
2
by: waylonflinn | last post by:
I'm looking for a way to invoke methods with an arbitrary number of parameters of arbitrary type from within a single method, when those parameters are known at the time of invocation of the...
9
by: Hans-Jürgen Philippi | last post by:
Hi group, let's say I have a 'Person' class with properties like 'FirstName', 'LastName', 'Birthday' and so on. Now I overload the 'Person' ToString() method with an implementation...
4
by: Jon Skeet [C# MVP] | last post by:
On Aug 11, 5:11 am, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com> wrote: Exactly. My favourite example is Thread.Sleep. Suppose this code were valid (its equivalent in Java is, for example): ...
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: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
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: 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...
1
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
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.