How to make C# COM class support parameterized properties from VB6 - c#

I've researched this question quite a bit, and while I've found a lot about C# and parameterized properties (using an indexer is the only way), I haven't found an actual answer to my question.
First, what I'm trying to do:
I have an existing COM DLL written in VB6 and I'm trying to create a C# DLL that uses a similar interface. I say similar because the VB6 DLL is only used with late binding, so it doesn't have to have the same GUIDs for the calls (that is, it doesn't have to be "binary compatible"). This VB6 COM DLL uses parameterized properties in a few places, which I know aren't supported by C#.
When using a VB6 COM DLL with parameterized properties, the reference in C# will access them as methods in the form "get_PropName" and "set_PropName". However, I'm going in the opposite direction: I'm not trying to access the VB6 DLL in C#, I'm trying to make a C# COM DLL compatible with a VB6 DLL.
So, the question is: How do I make getter and setter methods in a C# COM DLL that appear as a single parameterized property when used by VB6?
For example, say the VB6 property is defined as follows:
Public Property Get MyProperty(Param1 As String, Param2 as String) As String
End Property
Public Property Let MyProperty(Param1 As String, Param2 As String, NewValue As String)
End Property
The equivalent in C# would be something like this:
public string get_MyProperty(string Param1, string Param2)
{
}
public void set_MyProperty(string Param1, string Param2, ref string NewValue)
{
}
So, how would I make those C# methods look like (and function like) a single parameterized property when used by VB6?
I tried creating two methods, one called "set_PropName" and the other "get_PropName", hoping it would figure out that they're supposed to be a single parameterized property when used by VB6, but that didn't work; they appeared as two different method calls from VB6.
I thought maybe some attributes needed to be applied to them in C# so that they'd be seen as a single parameterized property in COM and VB6, but I couldn't find any that seemed appropriate.
I also tried overloading the methods, removing "get_" and "set_", hoping it would see them as a single property, but that didn't work either. That one generated this error in VB6: "Property let procedure not defined and property get procedure did not return an object".
I'm almost positive that there should be a way of doing this, but I just can't seem to find it. Does anyone know how to do this?
Update:
I took Ben's advice and added an accessor class to see if this could solve my problem. However, now I'm running into another issue...
First, here's the COM interface I'm using:
[ComVisible(true),
Guid("94EC4909-5C60-4DF8-99AD-FEBC9208CE76"),
InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface ISystem
{
object get_RefInfo(string PropertyName, int index = 0, int subindex = 0);
void set_RefInfo(string PropertyName, int index = 0, int subindex = 0, object theValue);
RefInfoAccessor RefInfo { get; }
}
Here's the accessor class:
public class RefInfoAccessor
{
readonly ISystem mySys;
public RefInfoAccessor(ISystem sys)
{
this.mySys = sys;
}
public object this[string PropertyName, int index = 0, int subindex = 0]
{
get
{
return mySys.get_RefInfo(PropertyName, index, subindex);
}
set
{
mySys.set_RefInfo(PropertyName, index, subindex, value);
}
}
}
Here's the implementation:
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid(MySystem.ClassId)]
[ProgId("MyApp.System")]
public class MySystem : ISystem
{
internal const string ClassId = "60A84737-8E96-4DF3-A052-7CEB855EBEC8";
public MySystem()
{
_RefInfo = new RefInfoAccessor(this);
}
public object get_RefInfo(string PropertyName, int index = 0, int subindex = 0)
{
// External code does the actual work
return "Test";
}
public void set_RefInfo(string PropertyName, int index = 0, int subindex = 0, object theValue)
{
// External code does the actual work
}
private RefInfoAccessor _RefInfo;
public RefInfoAccessor RefInfo
{
get
{
return _RefInfo;
}
}
}
Here's what I'm doing to test this in VB6, but I get an error:
Set sys = CreateObject("MyApp.System")
' The following statement gets this error:
' "Wrong number of arguments or invalid property assignment"
s = sys.RefInfo("MyTestProperty", 0, 0)
However, this works:
Set sys = CreateObject("MyApp.System")
Set obj = sys.RefInfo
s = obj("MyTestProperty", 0, 0)
It appears that it's trying to use the parameters on the property itself and getting an error because the property has no parameters. If I reference the RefInfo property in its own object variable, then it applies the indexer properties correctly.
Any ideas on how to arrange this so that it knows to apply the parameters to the accessor's indexer, rather than attempting to apply it to the property?
Also, how do I do a +1? This is my first question on StackOverflow :-)
Update #2:
Just to see how it would work, I also tried the default value approach. Here's how the accessor looks now:
public class RefInfoAccessor
{
readonly ISystem mySys;
private int _index;
private int _subindex;
private string _propertyName;
public RefInfoAccessor(ISystem sys, string propertyName, int index, int subindex)
{
this.mySys = sys;
this._index = index;
this._subindex = subindex;
this._propertyName = propertyName;
}
[DispId(0)]
public object Value
{
get
{
return mySys.get_RefInfo(_propertyName, _index, _subindex);
}
set
{
mySys.set_RefInfo(_propertyName, _index, _subindex, value);
}
}
}
This works great for a "get". However, when I try setting the value, .NET flips out with the following error:
Managed Debugging Assistant 'FatalExecutionEngineError' has detected a
problem in 'blahblah.exe'.
Additional information: The runtime has encountered a fatal error. The
address of the error was at 0x734a60f4, on thread 0x1694. The error
code is 0xc0000005. This error may be a bug in the CLR or in the
unsafe or non-verifiable portions of user code. Common sources of this
bug include user marshaling errors for COM-interop or PInvoke, which
may corrupt the stack.
I'm assuming the problem is that .NET tried setting the value to the method, rather to the default property of the returned object, or something similar. If I add ".Value" to the set line, it works fine.
Update #3: Success!
I finally got this working. There's a few things to look for, however.
First, the default value of the accessor must return a scaler, not an object, like so:
public class RefInfoAccessor
{
readonly ISystem mySys;
private int _index;
private int _subindex;
private string _propertyName;
public RefInfoAccessor(ISystem sys, string propertyName, int index, int subindex)
{
this.mySys = sys;
this._index = index;
this._subindex = subindex;
this._propertyName = propertyName;
}
[DispId(0)]
public string Value // <== Can't be "object"
{
get
{
return mySys.get_RefInfo(_propertyName, _index, _subindex).ToString();
}
set
{
mySys.set_RefInfo(_propertyName, _index, _subindex, value);
}
}
}
Second, when using the accessor, you need to make the return type an object:
public object RefInfo(string PropertyName, int index = 0, int subindex = 0)
{
return new RefInfoAccessor(this,PropertyName,index,subindex);
}
This will make C# happy, since the default value is a COM thing (dispid 0) and not a C# thing, so C# expects a RefInfoAccessor to be returned, not a string. Since RefInfoAccessor can be coerced into an object, no compiler error.
When used in VB6, the following will now all work:
s = sys.RefInfo("MyProperty", 0, 0)
Debug.Print s
sys.RefInfo("MyProperty", 0, 0) = "Test" ' This now works!
s = sys.RefInfo("MyProperty", 0)
Debug.Print s
Many thanks to Ben for his help on this!

C# can do indexed properties, but these must be implemented using a helper class which has an indexer. This method will work with early-bound VB but not with late-bound VB:
using System;
class MyClass {
protected string get_MyProperty(string Param1, string Param2)
{
return "foo: " + Param1 + "; bar: " + Param2;
}
protected void set_MyProperty(string Param1, string Param2, string NewValue)
{
// nop
}
// Helper class
public class MyPropertyAccessor {
readonly MyClass myclass;
internal MyPropertyAccessor(MyClass m){
myclass = m;
}
public string this [string param1, string param2]{
get {
return myclass.get_MyProperty(param1, param2);
}
set {
myclass.set_MyProperty(param1, param2, value);
}
}
}
public readonly MyPropertyAccessor MyProperty;
public MyClass(){
MyProperty = new MyPropertyAccessor(this);
}
}
public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
var mc = new MyClass();
Console.WriteLine(mc.MyProperty["a", "b"]);
}
}
There is a tutorial here:
https://msdn.microsoft.com/en-us/library/aa288464(v=vs.71).aspx
Late-bound VB Workaround
This is a workaround which takes advantage of two facts about VB. One is that in the array index operator is the same as the function call operator - round brackets (parens). The other is that VB will allow us to omit the name of the default property.
Read-only Properties
If the property is get-only, you don't need to bother with this. Just use a function, and this will behave the same as array access for late-bound code.
Read-Write properties
Using the two facts above, we can see that these are equivalent in VB
// VB Syntax: PropName could either be an indexed property or a function
varName = obj.PropName(index1).Value
obj.PropName(index1).Value = varName
// But if Value is the default property of obj.PropName(index1)
// this is equivalent:
varName = obj.PropName(index1)
obj.PropName(index1) = varName
This means that instead of doing the this:
//Property => Object with Indexer
// C# syntax
obj.PropName[index1];
We can do this:
// C# syntax
obj.PropName(index1).Value
So here is the example code, with a single parameter.
class HasIndexedProperty {
protected string get_PropertyName(int index1){
// replace with your own implementation
return string.Format("PropertyName: {0}", index1);
}
protected void set_PropertyName(int index1, string v){
// this is an example - put your implementation here
}
// This line provides the indexed property name as a function.
public string PropertyName(int index1){
return new HasIndexedProperty_PropertyName(this, index1);
}
public class HasIndexedProperty_PropertyName{
protected HasIndexedProperty _owner;
protected int _index1;
internal HasIndexedProperty_PropertyName(
HasIndexedProperty owner, int index1){
_owner = owner; _index1 = index1;
}
// This line makes the property Value the default
[DispId(0)]
public string Value{
get {
return _owner.get_PropertyName(_index1);
}
set {
_owner.set_PropertyName(_index1, value);
}
}
}
}
Limitations
The limitation is that to work, this depends on the call being made in a context where the result is coerced to a non-object type. For example
varName = obj.PropName(99)
Since the Set keyword was not used, VB knows that it must get the default property for use here.
Again, when passing to a function which takes for example a string, this will work. Internally VariantChangeType will be called to convert the object to the correct type, which if coercing to a non-object will access the default property.
The problem may occur when passing directly as a parameter to a function which takes a Variant as an argument. In this case the accessor object will be passed. As soon as the object is used in a non-object context (e.g. an assignment or conversion to string) the default property will be fetched. However this will be the value at the time it is converted, not the time it was originally accessed. This may or may not be an issue.
This issue can be worked around however by having the accessor object cache the value it returns to ensure it is the value as at the time the accessor was created.

This feature you seek is usually called "indexed properties". The flavor that VB6 uses is the flavor supported by COM interfaces.
This IDL fragment is similar to what VB6 would generate, and shows what's going on under the hood:
interface ISomething : IDispatch {
[id(0x68030001), propget]
HRESULT IndexedProp(
[in, out] BSTR* a, // Index 1
[in, out] BSTR* b, // Index 2
[out, retval] BSTR* );
[id(0x68030001), propput]
HRESULT IndexedProp(
[in, out] BSTR* a, // Index 1
[in, out] BSTR* b, // Index 2
[in, out] BSTR* );
[id(0x68030000), propget]
HRESULT PlainProp(
[out, retval] BSTR* );
[id(0x68030000), propput]
HRESULT PlainProp(
[in, out] BSTR* );
};
IndexedProp is a String property that takes two String parameters as indices. Contrast with PlainProp, which is of course a non-indexed conventional property.
Unfortunately, C# has very limited support for COM-style indexed properties.
C# 4.0 supports consuming COM objects (written elsewhere) that implement a COM interface with indexed properties. This was added to improve interoperability with COM Automation servers like Excel. However, it doesn't support declaring such an interface, or creating an object that implements such a COM interface even if legally declared elsewhere.
Ben's answer tells you how to create indexed properties in C# - or at least something that results in an equivalent syntax in C# code. If you just want the syntax flavor while writing C# code, that works great. But of course it's not a COM-style indexed property.
This is a limitation of the C# language, not the .NET platform. VB.NET does support COM indexed properties, because they had the mandate to replace VB6 and therefore needed to go the extra mile.
If you really want COM indexed properties, you could consider writing the COM version of your object in VB.NET, and have that object forward calls to your C# implementation. It sounds like a lot of work to me. Or port all your code to VB.NET. It really depends on how badly do you want it.
References
C# Team Blog: FAQ on new features in C# 4.0:
But this feature is available only for COM interop; you cannot create your own indexed properties in C# 4.0.
Why C# doesn't implement indexed properties?
Eric Lippert answers
COM-style Indexed Properties in VB.NET: Property with parameter

Related

Why are we allowed to use const with reference types if we may only assign null to them?

The question is actually very straightforward. The following code throws the exception right below it:
class Foo
{
public const StringBuilder BarBuilder = new StringBuilder();
public Foo(){
}
}
Error:
Foo.BarBuilder' is of type 'System.Text.StringBuilder'. A const field
of a reference type other than string can only be initialized with
null.
MSDN says this, which I understand and it makes sense from const perspective:
A constant expression is an expression that can be fully evaluated at
compile time. Therefore, the only possible values for constants of
reference types are string and a null reference.
However, I don't see the reason why or where we would use null constant. So why in the first place that a reference type (other than string) can be defined with const if it can be only set to null and if it was a deliberate decision (which I believe it is) then where can we use constant with null values?
Update:
When we think of an answer, please let's think differently than "We have this so why not that..." context.
From MSDN
when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference and cannot appear as an l-value in an expression.
Because reference types (other than null, and strings which are special) need to be constructed at run time, the above would not be possible for reference types.
For reference types, the closest you can get is static readonly:
class Foo
{
// This is not a good idea to expose a public non-pure field
public static readonly StringBuilder BarBuilder = new StringBuilder();
public Foo(){
}
}
Unlike const substitution (in the calling code), static readonly creates a single shared instance of the reference type which has subtle differences if assembly versions are changed.
Although the reference cannot (normally) be reassigned, it doesn't preclude calling non-pure methods on the StringBuilder (like Append etc). This is unlike consts, where value types and strings are immutable (and arguably should be "eternal").
However, I don't see the reason why or where we would use null constant.
Null constants are useful as sentinel values.
For example, this:
public class MyClass
{
private const Action AlreadyInvoked = null;
private Action _action;
public MyClass(Action action) {
_action = action;
}
public void SomeMethod()
{
_action();
_action = AlreadyInvoked;
}
public void SomeOtherMethod()
{
if(action == AlreadyInvoked)
{
//...
}
}
}
Is much more expressive than this:
public class MyClass
{
//...
public void SomeMethod()
{
_action();
_action = null;
}
public void SomeOtherMethod()
{
if(action == null)
{
//...
}
}
}
The source code for the Lazy<T> class shows Microsoft used a similar strategy. Although they used a static readonly delegate that can never be invoked as a sentinel value, they could have just used a null constant instead:
static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate
{
Contract.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
return default(T);
};
As you state in the question, there is one reference type that can be put into a const reference - strings. The compiler special-cases this and puts the strings into the compiled output and allows them to be read into the reference type at runtime.
Of course this begs the question - why not have strings be the only reference types that can be const, as long as we're special-casing them anyway? To that, I can only speculate that adding a special case in the compiler is simpler and less problematic than adding a special case in the language. From a language perspective, a string is just a reference type, even if the compiler has special handling to create instances of it from string literals and compiled resources.
I think that you are asking that why reference type with null allow as a constant.
I think you are right that it does not make much sense but it is useful if you have designed your own library and if you want to compare with null but want to give special meaning ( like comparing with your library value only rather then directly null)
public class MyClass
{
public const MyClass MyClassNull = null;
public MyClass()
{
}
}
it usage like this.
object obj = GetMyClass();
if(obj == MyClass.MyClassNull) // This going to convert to actual null in MSIL.
{
}

Change value inside an (void) extension method

So I have this mock extension method which change a value to another value:
public static void ChangeValue(this int value, int valueToChange)
{
value = valueToChange;
}
When I try using it:
int asd = 8;
asd.ChangeValue(10);
Debug.Log(asd);
It returns 8 instead of 10.
While the value did change inside the ChangeValue method, it didn't change the value of "asd". What do I need to add to the method, to make it update "asd"?
You can't do that without using either a return value, or a ref parameter. The latter doesn't work alongside this (extension methods), so your best bet is a return value (rather than void).
The old answer is not valid anymore since newer C# versions support this ref. For further details refer to this answer.
Old Answer:
int is a struct so it's a value-type. this means that they are passed by value not by reference. Classes are reference-types and they act differently they are passed by reference.
Your option is to create static method like this:
public static void ChangeValue(ref int value, int valueToChange)
{
value = valueToChange;
}
and use it:
int a = 10;
ChangeValue(ref a, 15);
Old question, but on newer versions of C# it looks like you can now do this for value types by using the this and ref keywords together. This will set value to be the same as valueToChange, even outside of this extension method.
public static void ChangeValue(this ref int value, int valueToChange)
{
value = valueToChange;
}
I believe this change was made to the compiler on version 15.1, which I think corresponds to C# 7 (or one of its sub versions). I did not immediately find a formal announcement of this feature.
According to this answer: https://stackoverflow.com/a/1259307/1945651, there is not a way to do this in C#. Primitive types like int are immutable, and cannot be modified without an out or ref modifier, but the syntax won't allow out or ref here.
I think your best case is to have the extension method return the modified value instead of trying to modify the original.
Apparently this is possible in VB.NET and if you absolutely needed it, you could define your extension method in a VB.NET assembly, but it is probably not a very good practice in the first place.
I know it's too late, but just for the record, I recently really wanted to do this, I mean...
someVariable.ChangeValue(10);
...apparently looks way neat than the following (which is also perfectly fine)
ChangeValue(ref someVariable, 10);
And I managed to achieve something similar by doing:
public class MyClass
{
public int ID { get; set; }
public int Name { get; set; }
}
public static void UpdateStuff(this MyClass target, int id, string name)
{
target.ID = id;
target.Name = name;
}
static void Main(string[] args)
{
var someObj = new MyClass();
someObj.UpdateStuff(301, "RandomUser002");
}
Note that if the argument passed is of reference type, it needs to be instantiated first (but not inside the extension method). Otherwise, Leri's solution should work.
Because int is value type, so it copied by value when you pass it inside a function.
To see the changes outside of the function rewrite it like:
public static int ChangeValue(this int value, int valueToChange)
{
//DO SOMETHING ;
return _value_; //RETURN COMPUTED VALUE
}
It would be possible to do using ref keyowrd, but it can not be applied on parameter with this, so in your case, just return resulting value.

Passing enumeration value to Java constructor from C#

I've a requirement to run JAR files from C# using IKVM. The JAR contains a class whose constructor takes an enumeration as one of its parameter. The problem I'm facing is that when I try to create an instance of this class in C# using IKVM an IllegalArgumentException is thrown.
Java enum:
public class EventType{
public static final int General;
public static final int Other;
public static int wrap(int v);
}
Java Class:
public class A{
private EventType eType;
public A(EventType e){
eType = e;
}
}
C# Usage:
/* loader is the URLClassLoader for the JAR files */
java.lang.Class eArg = java.lang.Class.forName("A", true, loader);
/* Instantiate with the underlying value of EventType.General */
object obj = eArg.getConstructor(EventType).newInstance(0);
eArg is correctly loaded by the forName(..) method. However, the instantiation of the eArg class throws the IllegalArgumentException. There's no message in the exception except for the exception.TargetSite.CustomAttributes specifying that the method is not implemented. I've also tried to pass the constructor argument as a java.lang.Field object, but even that gave the same exception.
Does anyone have any suggestions on what I might be doing wrong?
Instead of passing 0 (the underlying value), you need to pass the (boxed) enum value. So this should work:
/* loader is the URLClassLoader for the JAR files */
java.lang.Class eArg = java.lang.Class.forName("A", true, loader);
/* Instantiate with the underlying value of EventType.General */
object obj = eArg.getConstructor(EventType).newInstance(EventType.General);
I am not 100% sure but I believe the problem is that in .NET, the default underlying type of enum is int but in Java you have EventType defined as a class. The constructor in Java is expecting an object but from .NET, you are trying to pass the equivalent of an int.

Patterns for simulating optional "out" parameters in C#?

I'm translating an API from C to C#, and one of the functions allocates a number of related objects, some of which are optional. The C version accepts several pointer parameters which are used to return integer handles to the objects, and the caller can pass NULL for some of the pointers to avoid allocating those objects:
void initialize(int *mainObjPtr, int *subObjPtr, int *anotherSubObjPtr);
initialize(&mainObj, &subObj, NULL);
For the C# version, the obvious translation would use out parameters instead of pointers:
public static void Initialize(out int mainObj, out int subObj,
out int anotherSubObj);
... but this leaves no way to indicate which objects are unwanted. Are there any well-known examples of C# APIs doing something similar that I could imitate? If not, any suggestions?
Well, you shouldn't be using int for the objects anyway - they should be references, i.e. out SomeMainType mainObj, out SomSubType subObj. That done, you can then use overloads, but this would be ungainly.
A better approach would be to return something with the 3 objects - a custom type, or in .NET 4.0 maybe a tuple.
Something like:
class InitializeResult {
public SomeMainType MainObject {get;set;}
public SomeSubType SubObject {get;set;}
...
}
public static InitializeResult Initialize() {...}
Re-reading it, it looks like the caller is also passing data in (even if only null / not-null), so out was never the right option. Maybe a flags enum?
[Flags]
public enum InitializeOptions {
None = 0, Main = 1, Sub = 2, Foo = 4, Bar = 8, ..
}
and call:
var result = Initialize(InitializeOptions.Main | InitializeOptions.Sub);
var main = result.MainObject;
var sub = result.SubObject;
The closest translation would be using ref and IntPtr
public static void Initialize(ref IntPtr mainObj, ref IntPtr subObj,
ref IntPtr anotherSubObj)
and specifying IntPtr.Zero for unwanted values.
But for me the question arises why you want to resemble the API that close unless you are trying to figure out a P/Invoke signature. Assuming mainObj has accessible references to both sub object something like
public static MainObjectType Initialize(bool initSubObj, bool initAnotherSubObj)
appears to be a much cleaner solution to me. In .NET 4 you can even make the boolean arguments optional or simulate this with overloads in pre .NET 4. If there are no accessible references to the sub objects you could return a simple container type holding the references.
You can provide overloads of the method that don't take out parameters, and call the overload that does :
public static void Initialize()
{
int mainObj;
int subObj;
int anotherSubObj;
Initialize(out mainObj, out subObj, out anotherSubObj);
// discard values of out parameters...
}
public static void Initialize(out int mainObj, out int subObj, out int anotherSubObj)
{
// Whatever...
}
But as suggested by Marc, you should probably consider using a more object oriented approach...

Store a reference to a value type?

I am writing a "Monitor" object to facilitate debugging of my app. This Monitor object can be accessed at run time from an IronPython interpreter. My question is, is it possible in C# to store a reference to a value type? Say I have the following class:
class Test
{
public int a;
}
Can I somehow store a "pointer" to "a" in order to be able to check it's value anytime? Is it possible using safe and managed code?
Thanks.
You cannot store a reference to a variable in a field or array. The CLR requires that a reference to a variable be in (1) a formal parameter, (2) a local, or (3) the return type of a method. C# supports (1) but not the other two.
(ASIDE: It is possible for C# to support the other two; in fact I have written a prototype compiler that does implement those features. It's pretty neat. (See http://ericlippert.com/2011/06/23/ref-returns-and-ref-locals/ for details.) Of course one has to write an algorithm that verifies that no ref local could possibly be referring to a local that was on a now-destroyed stack frame, which gets a bit tricky, but its doable. Perhaps we will support this in a hypothetical future version of the language. (UPDATE: It was added to C# 7!))
However, you can make a variable have arbitrarily long lifetime, by putting it in a field or array. If what you need is a "reference" in the sense of "I need to store an alias to an arbitrary variable", then, no. But if what you need is a reference in the sense of "I need a magic token that lets me read and write a particular variable", then just use a delegate, or a pair of delegates.
sealed class Ref<T>
{
private Func<T> getter;
private Action<T> setter;
public Ref(Func<T> getter, Action<T> setter)
{
this.getter = getter;
this.setter = setter;
}
public T Value
{
get { return getter(); }
set { setter(value); }
}
}
...
Ref<string> M()
{
string x = "hello";
Ref<string> rx = new Ref<string>(()=>x, v=>{x=v;});
rx.Value = "goodbye";
Console.WriteLine(x); // goodbye
return rx;
}
The outer local variable x will stay alive at least until rx is reclaimed.
No - you can't store a "pointer" to a value type directly in C#.
Typically, you'd hold a reference to the Test instance containing "a" - this gives you access to a (via testInstance.a).
Here is a pattern I came up with that I find myself using quite a bit. Usually in the case of passing properties as parameters for use on any object of the parent type, but it works just as well for a single instance. (doesn't work for local scope value types tho)
public interface IValuePointer<T>
{
T Value { get; set; }
}
public class ValuePointer<TParent, TType> : IValuePointer<TType>
{
private readonly TParent _instance;
private readonly Func<TParent, TType> _propertyExpression;
private readonly PropertyInfo _propInfo;
private readonly FieldInfo _fieldInfo;
public ValuePointer(TParent instance,
Expression<Func<TParent, TType>> propertyExpression)
{
_instance = instance;
_propertyExpression = propertyExpression.Compile();
_propInfo = ((MemberExpression)(propertyExpression).Body).Member as PropertyInfo;
_fieldInfo = ((MemberExpression)(propertyExpression).Body).Member as FieldInfo;
}
public TType Value
{
get { return _propertyExpression.Invoke(_instance); }
set
{
if (_fieldInfo != null)
{
_fieldInfo.SetValue(_instance, value);
return;
}
_propInfo.SetValue(_instance, value, null);
}
}
}
This can then be used like so
class Test
{
public int a;
}
void Main()
{
Test testInstance = new Test();
var pointer = new ValuePointer(testInstance,x=> x.a);
testInstance.a = 5;
int copyOfValue = pointer.Value;
pointer.Value = 6;
}
Notice the interface with a more limited set of template arguments, this allows you to pass the pointer to something that has no knowledge of the parent type.
You could even implement another interface with no template arguments that calls .ToString on any value type (don't forget the null check first)
You can create ref-return delegate. This is similar to Erik's solution, except instead of getter and setter it use single ref-returning delegate.
You can't use it with properties or local variables, but it returns true reference (not just copy).
public delegate ref T Ref<T>();
class Test
{
public int a;
}
static Ref<int> M()
{
Test t = new Test();
t.a = 10;
Ref<int> rx = () => ref t.a;
rx() = 5;
Console.WriteLine(t.a); // 5
return rx;
}
You can literally take a pointer to a value type using usafe code
public class Foo
{
public int a;
}
unsafe static class Program
{
static void Main(string[] args)
{
var f=new Foo() { a=1 };
// f.a = 1
fixed(int* ptr=&f.a)
{
*ptr=2;
}
// f.a = 2
}
}
class Test
{
private int a;
/// <summary>
/// points to my variable type interger,
/// where the identifier is named 'a'.
/// </summary>
public int A
{
get { return a; }
set { a = value; }
}
}
Why put yourself through all that hassle of writing complicated code, declaring identifiers everywhere linking to the same location? Make a property, add some XML code to help you outside the class, and use the properties in your coding.
I don't know about storing a pointer, don't think it's possible, but if you're just wanting to check its value, the safest way to my knowledge is to create a property of the variable. At least that way you can check its property at any time and if the variable is static, you wouldn't even have to create an instance of the class to access the variable.
Properties have a lot of advantages; type safety is one, XML tags another. Start using them!

Categories