Accessing a member causes a runtime error exception because marchal by reference class

Published on Thursday, July 7, 2011
c#

Sometimes in your code you might see a warning like following:

Accessing a member on ‘xxxx’ may cause a runtime exception because it is a field of a marshal-by-reference class

This warning occurs when you try to call a method, property, or indexer on a member of a class that derives from MarshalByRefObject, and the member is a value type. Objects that inherit from MarshalByRefObject are typically intended to be marshaled by reference across an application domain. If any code ever attempts to directly access the value-type member of such an object across an application domain, a runtime exception will occur. (from msdn)

runtimeError00

To resolve the warning, copy the member into a local variable firstly and call the method on that variable.

For our case, We just added a local variable and set the reference class to this local variable.

default:
    float tempPenW = vectShapes.CreationPenWidth;
    this.toolStripTextBox2.Text = tempPenW.ToString();
    break;