컴파일러 오류 CS1656
업데이트: 2007년 11월
오류 메시지
'read-only variable type'이므로 'variable'에 할당할 수 없습니다.
Cannot assign to 'variable' because it is a 'read-only variable type'
이 오류는 읽기 전용 컨텍스트에서 변수에 할당할 때 발생합니다. 읽기 전용 컨텍스트는 foreach 반복 변수, using 변수 및 fixed 변수를 포함합니다. 이 오류가 발생하지 않도록 하려면 using 블록, foreach 문 및 fixed 문의 statement 변수에 할당하지 말아야 합니다.
예제
다음 예제에서는 foreach 루프 내에서 컬렉션의 전체 요소를 바꾸려고 하기 때문에 CS1656 오류가 발생하는 경우를 보여 줍니다. 이 오류를 해결하는 한 가지 방법은 foreach 루프를 for 루프로 변경하는 것입니다. 여기에 표시되지 않은 또 다른 방법은 기존 요소의 멤버를 수정하는 것입니다. 이 작업은 구조체가 아니라 클래스에 대해 수행할 수 있습니다.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace CS1654_2
{
class 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
{
private List<Book> list;
static void Main(string[] args)
{
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)
{
// Cannot modify an entire element in a foreach loop
// even with reference types.
// Use a for or while loop instead
if(b.Title == "The C Programming Language")
b = new Book("Programming Windows, 5th Ed.", "Petzold", 29.95); //CS1654
}
//With a for loop you can modify elements
//for(int x = 0; x < prog.list.Count; x++)
//{
// if(prog.list[x].Title== "The C Programming Language")
// prog.list[x] = new Book("Programming Windows, 5th Ed.", "Petzold", 29.95);
//}
//foreach(Book b in prog.list)
// Console.WriteLine(b.Title);
}
}
}
다음 샘플에서는 foreach 루프 이외의 다른 컨텍스트에서 CS1656이 발생하는 경우를 보여 줍니다.
// CS1656.cs
// compile with: /unsafe
using System;
class C : IDisposable
{
public void Dispose() { }
}
class CMain
{
unsafe public static void Main()
{
using (C c = new C())
{
c = new C(); // CS1656
}
int[] ary = new int[] { 1, 2, 3, 4 };
fixed (int* p = ary)
{
p = null; // CS1656
}
}
}