method ref to arbitrary value type instance
From: Andrew (anonymous_at_discussions.microsoft.com)
Date: 02/13/04
- Next message: Double-A: "Re: OT OT Poll"
- Previous message: A-PK: "Re: SMS Phone Drive & VB.net"
- Next in thread: Jon Skeet [C# MVP]: "Re: method ref to arbitrary value type instance"
- Reply: Jon Skeet [C# MVP]: "Re: method ref to arbitrary value type instance"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 12 Feb 2004 17:21:04 -0800
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.cs
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 arguments
// 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 arguments
// u.cs(37,11): error CS1503: Argument '1': cannot convert from 'ref A' to 'ref System.ValueType'
}
}
- Next message: Double-A: "Re: OT OT Poll"
- Previous message: A-PK: "Re: SMS Phone Drive & VB.net"
- Next in thread: Jon Skeet [C# MVP]: "Re: method ref to arbitrary value type instance"
- Reply: Jon Skeet [C# MVP]: "Re: method ref to arbitrary value type instance"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|