This project is read-only.

Filed Ref's

Topics: C# Language Design
Oct 13, 2014 at 10:27 AM
Often we need fast dynamic read/write to field of Custom Object.

When I have Property I can get delegate to it and store and fast use but for filed I can not use this.

I want to have some TypeSafe struct
struct FieldRef<T>
{
    Object  _objRef;
    Int32    _offset;

    public T value
    {
        get { return __InternalReadField<T>( _objRef, _offset ); }
        set { __InternalWriteField<T>( _objRef, _offset, value ); }
    }
}
with these FIeld refs we can save references to fields and we can write
 List<FieldRef<Single>> _foo;

foreach( var fRef in _foo )
    fRef.Value = ...
Oct 15, 2014 at 5:19 PM
And additional some typed FieldRefs like
FiledRef<Single, MyClass>  foo;

//and then

foo = &MyClass.SomeSingleField;

foreach( var obj in SomeMyClassObjCollection )
{
    foo.SetValue( obj, randomValue );
}
Oct 15, 2014 at 7:35 PM
I could see some usefulness to having some Framework types that would implement a IReadableProperty<T> and/or IReadWriteProperty<T> and then having compiler features that would make it easy to generate an instance of such a type which is bound to a particular property or field. At present, if a method were to accept a parameter of type IReadWriteProperty<int>, a caller that wanted to expose field myField to such a method, and could trust that it would not share the passed-in property object inappropriately, would have to do something like:
  TheMethod(new ReadWritePropertyWrapper( ()=>return myField, (x)=>myField = x) );
I'm not sure what syntax would be best, but it would seem like it would be nicer if the code could be written as something like:
  TheMethod(get set myField);
Note that if TheMethod accepts a constrained generic compiler, a compiler-implemented implementation of IReadableProperty could avoid having to create any heap objects, if the compiler did something like:
private struct CompilerGeneratedXYZ12345 : IReadWritePropertyWrapper<int>
{
  private myType _baseRef;
  public CompilerGeneratedXYZ12345 (myType baseRef) { _baseRef = baseRef; }
  public int Value { get {return _baseRef.myField;} set { _baseRef.myField=value;} }
}
and rendered the above call as
TheMethod(new CompilerGeneratedXYZ12345 (this));
For such a feature to be really useful, though, I would think it would have to be developed in conjunction with the Framework team to determine what the semantics of the necessary types should be [among other things, if a method only wants a property to be usable by the caller until such time as the caller has returned, how should that feature be implemented].
Oct 19, 2014 at 3:36 PM
Edited Oct 19, 2014 at 3:38 PM
supercat wrote:
  TheMethod(new ReadWritePropertyWrapper( ()=>return myField, (x)=>myField = x) );
You could use expression trees to simplify this to:
TheMethod(new ReadWritePropertyWrapper<T>(() => myField));
Though that would require some more heap allocations.