-3

I would like to have a reference to a byte as a class member, but it shows me an error invalid token 'ref' in class member declaration any workaround?

class MCP
{
    public byte olRegister;
};

class IO
{ 
    byte --reference to olRegister--;
};
Quest
  • 2,764
  • 1
  • 22
  • 44
  • 2
    I've always thought 2 years of membership and ~1K reps should be enough to ask a good question. – EZI Aug 17 '15 at 16:01
  • What's wrong with `byte b`? – dcastro Aug 17 '15 at 16:02
  • `public WhateverType @ref { get; set; }`... But seriously consider changing the name of that property/member. – Ron Beyer Aug 17 '15 at 16:03
  • @dcastro I don't know.. i just need a reference to a byte as a class member. I'm don't know almost nothing about C# just trying to understand MS samples – Quest Aug 17 '15 at 16:03
  • @Quest it would also help if you actually *showed the code* where you get the error... – Ron Beyer Aug 17 '15 at 16:04
  • @Quest `ref` is used to annotate method parameters, where the argument is bound to a variable in an outer scope, and the method might make that variable point to a different object. What you need is a normal `byte` field, e.g. `private byte b;` – dcastro Aug 17 '15 at 16:05
  • @dcastro I've added the code.. But in your suggestion, changing `IO::refToAByte` will not change the value of `MCP::olRegister` – Quest Aug 17 '15 at 16:07
  • hint: you dont have to put `;` at the end of the class. its redundant. (in c# it does nothing) – M.kazem Akhgary Aug 17 '15 at 16:09
  • @M.kazemAkhgary Got used from C++ – Quest Aug 17 '15 at 16:10
  • @Quest Seems like you need a public *static* member.. `public static byte olRegister;` – L.B Aug 17 '15 at 16:12

1 Answers1

0

You can't do that in C#

One possible solution would be to wrap your byte in a reference type, create an instance of it, and inject it into an instance of MCP and IO.

public class Wrapped<T> where T: struct
{
    public Wrapped(T t)
    {
        Elem = t;
    }

    public T Elem { get; set;}
}

class MCP
{
    public Wrapped<byte> McpByte { get; set; }
};

class IO
{ 
    public Wrapped<byte> IoByte { get; set; }
};

var b = new Wrapped<byte>(someByte);

var mcp = new Mcp { McpByte = b };
var io = new Io { IoByte = b };


mcp.McpByte = someOtherByte;
Assert.Equal(someOtherByte, io.IoByte);

This might not be the best solution - but we can't tell without knowing more about the bigger picture.

dcastro
  • 66,540
  • 21
  • 145
  • 155