Click here to Skip to main content
14,639,057 members
Rate this:
Please Sign up or sign in to vote.
See more:
In the below code, getting an error as
Property or indexer 'string.this[int]' cannot be assigned to -- it is read only


Why it is set readonly without user set it as readonly?

private void function(string text)
        { 
            int index = 0;
            text[0] = 'a';

            while(index < text.Length)
            {
                Console.WriteLine("The characters of string are" + text[index]);
                index++;
            }
        }


		    
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

The Item indexed property of String class is readonly by nature, i.e. it is defined with only one property getter and no property setter.
This is not something to be chosen by user.

You may need a StringBuilder instead:
StringBuilder sb = new StringBuilder(text);
sb[0] = 'a';


Hope this helps.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Because strings are immutable in C#, see, for instance "string (C# Reference)"[^].
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100