>
>
>
V3189. The assignment to a member of th…


V3189. The assignment to a member of the readonly field will have no effect when the field is of a value type. Consider restricting the type parameter to reference types.

The analyzer has detected that a value is assigned to the member of the 'readonly' field, and the field may be of a value type. If the field is of a value type, no change to the field member will occur.

This error occurs because value types directly contain their own data. If the field type is explicitly defined as value type, the compiler will find such an error. However, if the field type is a generic parameter, the code will compile successfully. Because of this, there may be a situation when something is written to a member of the 'readonly' field, but the member's value does not change.

Example:

private interface ITable
{
  int Rows { get; set; }
}

private class Table<T> where T : ITable
{
  private readonly T _baseTable;

  public void SetRows(int x)
  {
    _baseTable.Rows = x;     // <=
  }
}

The class has the '_baseTable' field, the type of which is a generic parameter. In the 'SetRows' method, the argument's value is assigned to the 'Rows' property of this field.

Below is an example of using this class:

private struct RelationTable : ITable
{
  public int Rows { get; set; }
}
....
static void DoSomething()
{
  Table<RelationTable> table = new Table<RelationTable>();
  table.SetRows(10);
}

In this case, calling 'SetRows' will not affect the value of the 'Rows' property in any way. To protect the code from such errors, you need to add type constrains:

private interface ITable
{
  int Rows { get; set; }
}

private class Table<T> where T : class, ITable
{
  private readonly T _baseTable;

  public void SetRows(int x)
  {
    _baseTable.Rows = x;
  }
}