Property or Indexer 'string.this[int]' Cannot Be Assigned to -- It Is Read Only

The objective of this commodity is to familiarize you with the C# string, given the fact that cord manipulation is the most important feature in whatsoever programming language.

In this tutorial, yous'll learn:

What Is a C# Cord?

C# string blazon represents a series of Unicode characters, and it is used to store the text which is one of the nigh common types of information for variables. The fashion y'all tell C# that you are making a string is to put double quotes around the hardcoded text (also called cord literal). If y'all attempt to enclose a cord in unmarried quotes, the compiler takes the value every bit a char and generates runtime mistake.

To declare and initialize a string variable, you need to utilize string keyword, which nether the hood translated to the System.String class from .NET Framework. In other words, string is simply an alias for the grade System.String.

string strA = "Pirzada";

Where strA is the name of the string variable and "Pirzada" is the predefined textual content assigned to it. This creates a string object that contains "Pirzada".

Basically, the text "Pirzada" is treated internally as a sequential read-only assortment of Char objects (char[]) with an indexer. The representation of the cord content looks closely like this:

Annotation: String indexing starts with 0 so the index of the starting time character is 0, i is the index of the second graphic symbol, and so on.

You lot tin extract individual characters from a cord, as you would normally practice in an array using an indexer-like ([ ]) syntax:

char singleChar = strA[1]; Console.WriteLine(singleChar); // Prints i

Run Demo

However, you tin can't change the characters, like this:

strA[i] = 'a';

This would cause a compilation error with the bulletin "Property or indexer 'string.this[int]' cannot exist assigned to -- it is read only" because strings are immutable.

Run Demo

The for and foreach loop can be used to admission each graphic symbol in the string.

string strA = "Pirzada";  // for loop for(int i = 0; i < strA.Length; i++)     Console.Write(strA[i] + "  "); // Prints horizontally  // foreach loop foreach(char c in strA)     Console.Write(c + "  "); // Prints horizontally

Run Demo

OUTPUT

P i r z a d a

Characteristics of String Grade in C#

  • Immutable
  • Reference blazon
  • Can contain nix
  • Overloads the == operator

cord vs String

Technically, there is no difference. The string is a built-in alias for System.Cord.
Every bit far as coding conventions, Information technology's recommended to use string when declaring a string object, but for string methods employ class similar Cord..

cord stringObject = "Pirzada"; string stringMethod = String.Concat(strA, strB);

Strings Are Immutable in C#

C# strings are immutable, meaning the contents of a string object cannot be changed once the object is created, which is one of the interesting aspects of System.String form. What is happening backside the scenes, compiler actually creates a new string object each time to hold the new sequence of characters when assigned.
Note: C# string is a reference type.

Consider the post-obit code:

string strA = "Pirzada Rashid";

Kickoff, declared and initialized strA with the value "Pirzada Rashid". This allocates a new string object on the heap (managed heap).

string strB = strA;

strB is initialized with a new reference that points to the same string in retentiveness, so strB also contains the value "Pirzada Rashid".

Allow'south print the values of strA and strB.

Panel.WriteLine($"strA : {strA}"); Console.WriteLine($"strB : {strB}");  strA = strA.Remove(7);

Remove method returns a new object with the value "Pirzada", which is assigned to the strA variable.

Please note that Remove method does not change the existing string but returns a new cord every bit a issue. If you endeavor to delete characters without storing them in a variable, the changes would be lost.

Once again, impress the values of strA and strB.

Console.WriteLine($"strA : {strA}"); // value changed Console.WriteLine($"strB : {strB}"); // value all the same same

Changing the value of strA has no consequence on strB, which differs from the usual behavior for reference types. Why is that?

Since Strings are immutable, when you lot change the value of strA, instead of replacing the original value, an entirely new object with new reference is allocated on the heap for the new value "Pirzada" and the former reference is discarded. The strB variable even so points to the original object, so its value is unchanged in the process. This is how the system implements immutable.

Run Demo

OUTPUT

strA : Pirzada Rashid
strB : Pirzada Rashid

strA : Pirzada
strB : Pirzada Rashid

C# Null String

Technically, a null indicates that the alleged string has not been initialized with a valid value, meaning no object is currently associated with the variable.

The null value identified with the nada keyword, indicates that a variable is gear up to nothing.

string strA = null;

To test whether a string is zilch or non, use the condition

if (strA == zippo); // true

Attempting to call methods or properties on strA throws a NullReferenceException.

Console.WriteLine(strA.Length);

Run Demo

C# Empty String

An empty string is a string with no characters, meaning nothing-length string.

Y'all can initialize a string variable to an empty string, like this:

string strA = ""; // or string strA = String.Empty;

Recommended manner to initialize string is to use String.Empty value, which is same equally (" "). From the readability, this sort of code is much more straightforward and less decumbent to misinterpretation.

Console.WriteLine(strA.Length); // Prints 0

Run Demo

String.Empty is a static read-but field, while " " (quote-quote) is a compile time abiding that creates a new empty string object on the heap with empty content.

string strA; // Un-initialized - value null;   string strA = null; // Initialized with zip string strA = "";  // empty string string strA = cord.Empty; // empty string

Strings and Equality

I take initialized ii string variables, strA and strB.

string strA = "programmer"; cord strB = "programmer";

Equals() and String.Equals()

Nearly of the fourth dimension, when comparing ii String objects, you want to determine whether two objects accept the same character sequence or not. In this case, you need to use the String class .Equals() method to properly compare two strings for equality.

bool strC = strA.Equals(strB);   // OR bool strC = strB.Equals(strA);   Console.WriteLine(strC); // Prints: Truthful

Note: Equality test is example-sensitive.

.Equals is a user-friendly case method, which compares two strings strA & strB to run into if they contain the same content and returns the Boolean result of truthful if the value of strA is the same as the value of strB; otherwise, false.

Yous can use static Cord.Equals method to check whether strA & strB are equal, which returns Boolean value of True/Simulated every bit a upshot.

bool strC = String.Equals(strA,strB);  Panel.WriteLine(strC); // Prints: Truthful

Run Demo

If first string is null and you try to invoke .Equals() method on it, an exception of type NullReferenceException is thrown with the bulletin 'Object reference not gear up to an example of an object'.

string strA = null; string strB = "programmer";  Console.WriteLine(strA.Equals(strB)); // Throws Exception

Instead, utilize static String.Equals method or == operator for comparing Strings because both are nada-safe.

Console.WriteLine(String.Equals(strA, strB)); // No Exception Panel.WriteLine(strA==strB); // No Exception

Run Demo

If you lot have to compare two strings, ignoring instance considerations (capital letter / lowercase), then you lot could use .Equals() method with the parameter StringComparison.CurrentCultureIgnoreCase.

Let'due south compare "developer" with "Programmer" with capital D, result would be truthful:

string strA = "programmer"; string strB = "Developer";  Console.WriteLine(strA.Equals(strB, StringComparison.CurrentCultureIgnoreCase)); // True

Nevertheless, without the StringComparison.CurrentCultureIgnoreCase parameter, the method will return fake as a result.

Console.WriteLine(strA.Equals(strB)); // False

Run Demo

string equals vs == Operator

When the == operator is used, y'all actually use overloaded version of the operator at compile-time to compare the value of two strings. In C#, there is no divergence between == operator and .Equals() method as long as both are of type string except the possibility of calling .Equals() on a null which throws NullReferenceException. Y'all can see operator overload implementation here.

Console.WriteLine(strA==strB); // Prints: True

Note: == operator calls String.Equals() method, when both sides of the operator are cord expressions.

By default, the == operator tests for reference equality to run across if two variables are pointing to the same object in computer's memory. This behavior is for reference types where == has no overload and the default implementation is used past the framework. Consider the following case:

object objA = "Codebuns"; object objB = objA;     object objC = new Cord(new char[] { 'C', 'o', 'd', 'e', 'b', 'u', 'n', 'south' });  Panel.WriteLine(objA == objC); // Unlike reference: False Panel.WriteLine(objA == objB); // Aforementioned reference: True Console.WriteLine(objA.Equals(objC)); // Same Value: True

Notation: objA & objC refer to 2 different string objects, but both comprise the same value.

In the to a higher place code, the == operator is invoked on type object, which compares object references by default. This comparison returns False because both variables refer to the ii different objects. On the other hand, Equals will return True because it actually compares the value and both the variables despite different references have the same value.

Run Demo

C# String Concatenation (kon-kat-en-ay-shun)

I have already discussed these topics in detail. Please click on the links below to read more.

The Old Fashion
String.Concat( ) and "+"
String.Join( )
String.Format( )

The New Mode
Cord Interpolation

C# String Methods and Properties

C# string course provides a lot of useful methods and properties to manipulate strings. Some of the most commonly used are listed below.

C# String Properties

Property Clarification
Length C# string length property returns the number of characters in the electric current String.
[alphabetize] Indexer returns the character at the specified position.

C# String Methods

Method Description
Compare() C# compare method compares ii cord objects.
Equals() C# equals method returns Boolean value after comparing 2 strings.
Contains() C# contains method checks and returns a Boolean value if specified character or cord exists in the current cord.
StartsWith() C# StartsWith method determines whether the beginning of the electric current string matches the specified string.
EndsWith() C# EndsWith method determines whether the end of the current string matches the specified string.
Substring() C# Substring method retrieves a substring from a string.
IndexOf() C# IndexOf method returns the alphabetize of the kickoff occurrence of a specified string within the current string.
LastIndexOf() C# LastIndexOf method returns the alphabetize of the last occurrence of a specified string within the current cord.
Insert() C# Insert method returns a new string with a substring inserted at a specified index in the current string.
Remove() C# Remove method removes the specified number of characters from a string.
Concat() C# Concat method concatenates two cord objects together.
Bring together() C# Bring together method joins an array of strings together with the specified separator between each element.
Replace() C# Replace method replaces all occurrences of the grapheme in the current string with a unlike grapheme.
Separate() C# Split method splits a string into substrings based on the supplied value.
ToLower() C# ToLower method converts and returns a lowercase cord.
ToUpper() C# ToUpper method converts and returns an uppercase string.
Trim() C# Trim method removes all the whitespace or a ready of specified characters from the get-go and end of the electric current string.
TrimStart() C# TrimStart method removes all the whitespace or a set of specified characters from the kickoff of the electric current cord.
TrimEnd() C# TrimEnd method removes all the whitespace or a set of specified characters from the terminate of the current cord.
ToCharArray() C# ToCharArray method converts a string into an array of character.
IsNullOrEmpty() C# IsNullOrEmpty method checks whether a string variable is aught or an empty string ("").
IsNullOrWhitespace() C# IsNullOrWhitespace method checks whether a string variable is null, empty, or consists simply of white-infinite characters.

C# Cord Code Examples

Permit's look at the examples.

Length

C# cord Length is the read-merely holding which returns the total number of characters in the current string. Yous cannot modify the length of a string because it is immutable.

cord strA = "Hello, Pirzada"; Console.WriteLine(strA.Length); // xi

Run Demo

Compare()

C# cord Compare method compares two specified String objects in lexicographical guild and returns an integer that indicates their relative position in the sort order.

String.Compare returns an integer value, which can be equal to zero, greater than nil or less than zero.

  • 0 if same position.
  • +1 if strA follows strB.
  • -1 if strA precedes strB.

Co-ordinate to MSDN
Use the String.Compare method to sort strings, not to check for equality.

cord strA = "Pirzada"; string strB = "pirzada";

1 – Method Signature: int Compare(string strA, string strB);

int order = String.Compare(strA, strB);  switch(social club) {      case 0:          Console.WriteLine($"{strA} and {strB} have the same position.");          intermission;      instance +1:          Console.WriteLine($"{strA} follows {strB}.");         break;      case -1:          Console.WriteLine($"{strB} precedes {strA}.");           interruption;  }
OUTPUT

Pirzada follows pirzada.

2 – Method Signature: int Compare (string strA, string strB, bool ignoreCase);

The third parameter ignoreCase is optional, which is always set to "True" to ignore instance-sensitive match. Use "Imitation" to enable case-sensitive comparison.

int lodge = String.Compare(strA, strB, truthful);  switch(order) {      case 0:          Console.WriteLine($"{strA} and {strB} accept the aforementioned position.");          intermission;      case +1:          Console.WriteLine($"{strA} follows {strB}.");         break;      instance -1:          Console.WriteLine($"{strB} precedes {strA}.");           break;  }
OUTPUT

Pirzada and pirzada take the same position.

Run Demo

Equals()

C# string Equals method is used to test whether ii strings are equal and returns true if the strings are identical, false otherwise.

string strA = "Pirzada"; string strB = "Hello Codebuns.com";

ane – Method Signature: bool Equals(cord value);

Console.WriteLine(strA.Equals(strB)); // false Console.WriteLine(strA.Equals(strA)); // truthful

Note: Throws NullReferenceException if strA is null.

ii – Method Signature: bool Equals(string a, string b);

Console.WriteLine(String.Equals(strA, strB)); // false Console.WriteLine(String.Equals(strA, strA)); // true

strA and strB can be cord variables or cord literals, like this.

"Pirzada".Equals(strA); // true

Run Demo

Contains()

C# string Contains method returns a Boolean true/false indicating whether a specified substring exists within the electric current string.

Method Signature: bool Contains(cord value);

string strB = "Hello, Codebuns.com"; Console.WriteLine(strB.Contains("Codebuns")); // true Console.WriteLine(strB.Contains("Hmm")); // faux

Run Demo

StartsWith()

C# cord StartsWith method determines whether the start of the electric current cord instance matches a specified string.

Method Signature: bool StartsWith(string value);

string strA = "Pirzada"; Console.WriteLine(strA.StartsWith("Pi")); // true Console.WriteLine(strA.StartsWith("da")); // false

Run Demo

EndsWith()

C# cord EndsWith method determines whether the end of a current string case matches a specified cord.

Method Signature: bool EndsWith(string value);

string strA = "Pirzada"; Console.WriteLine(strA.EndsWith("da")); // true Console.WriteLine(strA.EndsWith("Pi")); // fake

Run Demo

Substring()

C# string Substring method extracts part of a string, called substring from a longer string. At that place are two overloads for this method.

string strB = "Hello Codebuns.com";

one – Method Signature: cord Substring(int startIndex);

Red is the index of the starting position, where the substring starts. Past default, information technology substrings all remaining characters.

Console.WriteLine(strB.Substring(6));
OUTPUT

Codebuns.com

2 – Method Signature: string Substring (int startIndex, int length);
The beginning argument specifies the index of the starting position to excerpt followed past the length (number of characters to extract).

Console.WriteLine(strB.Substring(six, 8));
OUTPUT

Codebuns

Run Demo

IndexOf()

C# cord IndexOf method searches for a specified string within another string, returning the position of the found cord with a numeric index value. The method returns -1 if the grapheme or string non plant.

string strB = "Hullo Codebuns.com";

one – Method Signature: int IndexOf(char value);

Console.WriteLine(strB.IndexOf('b')); // 10

ii – Method Signature: int IndexOf(string value);

Panel.WriteLine(strB.IndexOf("com")); // 15

3 – Method Signature: int IndexOf(char value, int startIndex);
The kickoff parameter is the 'search string' yous are searching for and the second is the numeric position where you want to brainstorm the search.

Blood-red indicates the starting position of search inside the current cord, forward.

Panel.WriteLine(strB.IndexOf('C', 1)); // half-dozen

Panel.WriteLine(strB.IndexOf('C', ten)); // -i

4 – Method Signature: int IndexOf(cord value, int startIndex);

Console.WriteLine(strB.IndexOf("Code", 3)); // 6

Run Demo

OUTPUT

10
15
6
-ane
6

LastIndexOf()

C# string LastIndexOf method returns the index position of the final occurrence of a particular character/substring within the target string. Method returns -1 if the character or string non found.

cord strB = "How-do-you-do Codebuns.com";

i – Method Signature: int LastIndexOf(string value);

Searches from the terminate towards the start.

Console.WriteLine(strB.LastIndexOf(".com")); // 14

2 – Method Signature: int LastIndexOf(char value);

Console.WriteLine(strB.LastIndexOf('o')); // xvi

3 – Method Signature: int LastIndexOf (char value, int startIndex);

Cerise indicates the starting position of search towards the beginning within the cord.

Console.WriteLine(strB.LastIndexOf('eastward', 14)); // 9

4 – Method Signature: int LastIndexOf(string value, int startIndex);

Console.WriteLine(strB.LastIndexOf("Code", 12)); // 6

Run Demo

OUTPUT

14
16
9
6

IndexOf() vs LastIndexOf()

The but departure between these methods is the search direction. Allow us have a very simple example.

string strB = "Howdy Codebuns.com";

indexOf()
Search starts from the beginning index 0 towards the last index 17 and returns the specified grapheme/substring within the provided string.

The starting time occurrence of o found at the index 4.

Panel.WriteLine(strB.IndexOf('o')); // 4

LastIndexOf()
Search starts from the last alphabetize 17 towards the first index 0 and returns the specified grapheme/substring within the provided string.

The first occurrence of o institute at the index 16, because of the opposite search direction. The concluding occurrence, if you take the search from the first index 0 to the concluding index 17.

Console.WriteLine(strB.LastIndexOf('o')); // xvi

Run Demo

Insert()

C# cord Insert method returns a new string in which a provided string is inserted at a specified index position in the current string.

Method Signature: string Insert (int startIndex, string value);

string strA = "Pirzada"; Console.WriteLine(strA.Insert(0, "Howdy, "));

Run Demo

OUTPUT

Hi, Pirzada

Remove()

C# string Remove method returns a new string in which a specified number of characters from the electric current cord are deleted.

cord strB = "Howdy Codebuns.com";

1 – Method Signature: cord Remove (int startIndex);

Blood-red indicates the index of the starting position, from where all the characters volition be removed from the cord.

Console.WriteLine(strB.Remove(5));
OUTPUT

Hello

ii – Method Signature: cord Remove (int startIndex, int count);

The showtime parameter is the index of the starting position followed by the number of characters to remove from the string.

Console.WriteLine(strB.Remove(5, 9));
OUTPUT

Hello.com

Run Demo

Concat()

C# cord Concat is the static method which concatenates one or more instances of String.

Method Signature: string Concat (cord str0, string str1);

string strA = "Pirzada"; string strC = "Hello ";  Console.WriteLine(String.Concat(strC, strA)); Console.WriteLine(String.Concat(strC, "Codebuns.com"));

Run Demo

OUTPUT

Hullo Pirzada
Hello Codebuns.com

Bring together()

C# string Join method concatenates the elements of an array, using the specified separator between each element.

string[] strArray = {"111","222","3333"};

i – Method Signature: cord Join (string separator, cord[] value, int startIndex, int count);

Panel.WriteLine(String.Join("|", strArray, 0, two)); Console.WriteLine(String.Join("/", strArray, ane, 2));
OUTPUT

111|222
222/3333

2 – Method Signature: string Join (string separator, params cord[] value);

Console.WriteLine(String.Join("-", strArray));
OUTPUT

111-222-3333

Run Demo

Supercede()

C# string Replace method searches and replaces whatever string with another string. Search is case-sensitive and must match exactly.

string strC = "111-222-3333";

ane – Method Signature: string Replace (string oldValue, string newValue);

OUTPUT

444-222-3333

Console.WriteLine(strC.Replace("111", "444"));

2 – Method Signature: cord Replace (char oldChar, char newChar);

Console.WriteLine(strC.Supersede('-', '/'));
OUTPUT

111/222/3333

Run Demo

Split()

C# cord Split method returns an assortment of string that contains the substrings after splitting the source string at the specified points.

string strC = "111-222-3333";

Method Signature: string[] Split (params char[] separator);

The post-obit code obtains the assortment of substrings by splitting the strC variable value at each — graphic symbol.

string[] strArray = strC.Split up('-');

Next, you loop through the array using foreach and prints out all the array elements to the panel:

foreach (string str in strArray) 	Console.WriteLine(str);

Run Demo

OUTPUT

111
222
3333

Splitting String by Multiple Separators
The post-obit code splits the content of a string into the array of substrings using multiple delimiting characters passed every bit an argument of the method.

string strA = "ane,2/iii#4,v,6";  char[] separators = new char[] {',', '/', '#' }; cord[] strArray = strA.Divide(separators);  foreach (string str in strArray)     Console.Write(str); // Prints horizontally

Run Demo

OUTPUT

123456

ToUpper()

C# string ToUpper method returns a copy of the current string converted to uppercase.

Method Signature: cord ToUpper();

cord strA = "Pirzada"; Panel.WriteLine(strA.ToUpper());

Run Demo

OUTPUT

PIRZADA

ToLower()

C# string ToLower method returns a copy of the current string converted to lowercase.

Method Signature: string ToLower();

string strA = "Pirzada"; Panel.WriteLine(strA.ToLower());

Run Demo

OUTPUT

pirzada

Trim()

C# string Trim method gets rid of both the leading and trailing spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: cord Trim();

Panel.WriteLine(strD.Trim());

Run Demo

OUTPUT

C# Programming

TrimStart()

C# cord TrimStart method gets rid of the leading spaces, simply not the trailing spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: string TrimStart();

Console.WriteLine(strD.TrimStart());

Run Demo

OUTPUT

C# Programming

TrimEnd()

C# cord TrimEnd method gets rid of the trailing spaces, but not the leading spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: string TrimEnd();

Console.WriteLine(strD.TrimEnd());

Run Demo

OUTPUT

C# Programming

ToCharArray()

C# string ToCharArray method returns an assortment of Unicode character later converting the provided string.

string strA = "Hello, Pirzada";

one – Method Signature: char[] ToCharArray();

char[] charArray = strA.ToCharArray(); // Convert String to Char Array foreach (char ch in charArray)   	Panel.WriteLine(ch);
OUTPUT

H
i
,

P
i
r
z
a
d
a

2 – Method Signature: char[] ToCharArray(int startIndex, int length);

Red indicates the alphabetize of the starting position followed by a length (number of characters to excerpt).

char[] charArray = strA.ToCharArray(iv, 5); foreach (char ch in charArray)   	Console.WriteLine(ch);
OUTPUT

P
i
r
z
a

Run Demo

String.IsNullOrEmpty()

Starting with C# version 2005, Microsoft introduced a Boolean string method IsNullOrEmpty() to test whether the value of a cord is blank, empty, or nix.

IsNullOrEmpty() is equivalent to: south == cipher || south == Cord.Empty;

Let's look at the example.

string strA = null; string strB = String.Empty; string strC = "Pirzada"; cord strD = "";  Panel.WriteLine(check(strA)); // True Console.WriteLine(check(strB)); // Truthful Console.WriteLine(cheque(strC)); // Fake Panel.WriteLine(bank check(strD)); // Truthful  public static bool cheque(string str)  {       render Cord.IsNullOrEmpty(str); }

Run Demo

String.IsNullOrWhitespace()

C# cord IsNullOrWhitespace method checks whether a specified string is null, empty, or consists but of white-infinite characters.

IsNullOrWhiteSpace() is equivalent to: Cord.IsNullOrEmpty(value) || value.Trim().Length == 0;

Method Signature: bool IsNullOrWhiteSpace(string value);

Allow's look at the example.

string strA = nothing; cord strB = String.Empty; string strC = "Pirzada"; string strD = ""; string strE = "\t"; string strF = " \n ";  Console.WriteLine(check(strA)); // True Console.WriteLine(cheque(strB)); // True Console.WriteLine(bank check(strC)); // Imitation Panel.WriteLine(bank check(strD)); // True Console.WriteLine(check(strE)); // Truthful Console.WriteLine(check(strF)); // True  public static bool bank check(string str)  {       return String.IsNullOrWhiteSpace(str); }

Run Demo

ToString( )

C# ToString method converts the value of an object to a regular cord (returns string representation).

Method Signature: string ToString();

int number = 22;   string strNumber = number; // Error: Cannot implicitly convert type 'int' to 'string'  // Number converted to type Cord string strNumber = number.ToString();  Console.WriteLine("Number -> " + strNumber); // Number -> 22

Run Demo

Useful Articles

  • C# Online Editors
  • C# variables
  • C# StringBuilder
  • C# Escape Sequences

C# Reference | Microsoft Docs

  • String.IsNullOrEmpty(Cord) Method
  • Equality operators

bellawerly.blogspot.com

Source: https://codebuns.com/csharp-basics/string/

0 Response to "Property or Indexer 'string.this[int]' Cannot Be Assigned to -- It Is Read Only"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel