473,785 Members | 2,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.WriteLi ne("f: obj={0}", obj);

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

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

static void i(ref System.ValueTyp e obj
{ Console.WriteLi ne("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.ValueTyp e)' has some invalid argument
// u.cs(37,11): error CS1503: Argument '1': cannot convert from 'ref A' to 'ref System.ValueTyp e


Jul 21 '05 #1
9 2067
Andrew <an*******@disc ussions.microso ft.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.co m>
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*******@disc ussions.microso ft.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.co m>
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*******@disc ussions.microso ft.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.co m>
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*******@disc ussions.microso ft.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.co m>
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*******@disc ussions.microso ft.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.co m>
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
1907
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 with value if 'another' in items: value = items # do something else with value
24
2630
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 you pass a Value-Type to method call ,Boxing and Unboxing would happen,Consider the following snippet: int a=1355; myMethod(a); ......
18
4750
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 class where only the "searched" property has a value. I expected to get the index into the arraylist where I could then get the entire class instance. However, the 'indexof' is never calling my overloaded, overrides Equals method. Here is the...
44
2772
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
287
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 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...
19
2446
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; //every class may have this statement self.hello = function() {
2
1978
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 containing method. I don't see a reason why this shouldn't work. I also can't find the language feature which implements it. More details below. As part of the creation of a set of classes for doing unit testing I want to create a generic...
9
2864
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 ToString(string PlaceholderString) of the following purpose: When someone calls ToString("{LastName}, {FirstName}") on a given Person instance, the expected result is e.g. "Doe, John" for this object, that is: Any {property placeholder} is replaced by the...
4
1915
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): ThreadStart ts = SomeMethodToRun; Thread thread = new Thread(ts); thread.Start(); thread.Sleep(500);
0
9645
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
9481
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
10155
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...
1
10095
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9954
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
8979
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...
1
7502
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
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.