Assigning a value to the readonly property works with a fixed value, but not with a variable

Using the Entity Framework to create an index and the following code:

var op = new CreateIndexOperation
    {
        Columns = { "COL_A", "COL_B", "COL_C" },
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });

This compiles and works as expected. Trying to reorganize this into the following method (simplified for this example):

private void AddIndex(params string[] columns)
{
    var op = new CreateIndexOperation
    {
        Columns = columns.ToList(),
        IsUnique = true,
        Name = "INDEX_NAME",
        Table = "TABLE_NAME"
    });
}

This method throws the following compiler error:

Property or Indexer 'IndexOperation.Columns' cannot be assigned to -- it is read only

Looking at the MSDN documentation , it looks right, and the property Columnshas no setter. However, if so, why does the first block of code not throw a compiler error, and the second does, where am I trying to set this value from a variable?

+4
source share
1 answer

, collection-initializer, (, , ). , - :

var op = new CreateIndexOperation();
op.Columns.Add(...);
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";

, , , .

, , , Columns . NullReferenceException.

, , :

var op = new CreateIndexOperation();
op.Columns = columns.ToList();
op.IsUnique = true;
op.Name = "INDEX_NAME";
op.Table = "TABLE_NAME";
+2

Source: https://habr.com/ru/post/1673620/


All Articles