C# Error
CS1654 – Cannot modify members of ‘{0}’ because it is a ‘{1}’
Reason for the Error & Solution
Cannot modify members of ‘variable’ because it is a ‘read-only variable type’
This error occurs when you try to modify members of a variable which is read-only because it is in a special construct.
One common area that this occurs is within loops. It is a compile-time error to modify the value of the collection elements. Therefore, you cannot make any modifications to elements that are , including . In a collection whose elements are , you can modify accessible members of each element, but any try to add or remove or replace complete elements will generate .
Example
The following example generates error CS1654 because Book
is a struct
. To fix the error, change the struct
to a .
using System.Collections.Generic;
using System.Text;
namespace CS1654
{
struct Book
{
public string Title;
public string Author;
public double Price;
public Book(string t, string a, double p)
{
Title=t;
Author=a;
Price=p;
}
}
class Program
{
List<Book> list;
static void Main(string[] args)
{
//Use a collection initializer to initialize the list
Program prog = new Program();
prog.list = new List<Book>();
prog.list.Add(new Book ("The C# Programming Language",
"Hejlsberg, Wiltamuth, Golde",
29.95));
prog.list.Add(new Book ("The C++ Programming Language",
"Stroustrup",
29.95));
prog.list.Add(new Book ("The C Programming Language",
"Kernighan, Ritchie",
29.95));
foreach(Book b in prog.list)
{
//Compile error if Book is a struct
//Make Book a class to modify its members
b.Price +=9.95; // CS1654
}
}
}
}