Hello to anyone reading this! This marks the third blog post I have done on my newly created blog in regard to the C# programming language. In my first technical blog post, I mentioned value types. To recap – I wrote about char, int, double, and bool. How to declare, assign, and modify those value type variables.
Reference Types Introduction
In this post I will be writing about the other kind of type – Reference Types. Similar to value type variables you have a process to declare and assign data to reference types. However, when you are assigning data to a reference type variable, you are really just referencing a memory location on the manage heap in memory. Essentially, you are assigning a reference to the underlying object rather than altering the object.
There are some keywords in the C# language that allow you to declare reference types:
- class
- interface
- delegate
- record
The C# language also has some built-in reference types:
- dynamic
- object
- string
For the sake of brevity, I will be writing about the string reference type in this post. For more information on the other options, stay tuned for future blog posts or I will link documentation regarding this topic in the additional resources below.
Strings in C#
I will be writing about a few key aspects of the string variable in C#.
- Difference between String and string declarations
- The string type
- Retrieving characters from a string
- String Interpolation
- String variable length
- String Comparison
- String Concatenation
The difference between String and string
If you are familiar with the Java programming language, you may be fairly comfortable with declaring Strings. In C#, you can declare a string using two separate types:
String thisIsOne = "Hello!";
string thisIsTwo = "Hello!";
So, what is the difference between the two variables? By using the lowercase keyword you are essentially accomplishing the same thing as using the uppercase one.
The lowercase keyword is an alias for the System.String class in .NET.
The string type
The string type is a sequence of zero or more Unicode characters. It is one of the most used variable types in C#. Strings in C# can be initialized using double quote marks. It cannot be initialized using single quotes as they are used to denote character literals.
string tryThis = 'Hello!'; // Will cause error
string tryThis = "Hello!"; // Correct way
Strings are immutable data, which means they cannot be changed once created. Any operation that attempts to modify the assignment will create a new string object.
You can declare a string using String or string in C#, but you must use double quotation marks, not single quotation marks.
Retrieve characters within the string
You can actually access individual characters in a string variable by using indexing. For example, in the example above there are six characters in the string variable tryThis. Indexing uses a zero-based counting system (0, 1, 2, 3, etc…).
string greeting = "Hello!";
char firstChar = greeting[0]; // 'H'
Use indexing to store a character from a string variable. Similar to arrays (stay tuned for future blog posts).
Add assigned variables into string variables
As a C# developer, you can use string interpolation to embed assigned variables into a string variable allowing you to make more robust applications.
string firstName = "Kyle";
string lastName = "Martin";
string greeting = $"Hello everyone, my name is {firstName} {lastName}.";
You must use the ‘$’ character prior to the first double quotation mark to tell the compiler you wish to add expressions into the string variable.
String Length
In C#, you can use a property to parse and see how many unicode characters are in a string. This is accomplished by using the ‘Length’ property.
string greeting = "Hello!";
int greetingLength = greeting.Length;
Console.Write(greetingLength); // Output: 6
If the string is assigned “null” it will throw a Null Reference Exception
String Comparison
The string class allows you to use a plethora of methods in order to compare strings in C#. The most commonly used methods are Equals, Compare, CompareOrdinal, StartsWith, EndsWith, Contains, IndexOf, and LastIndexOf. Here are some examples:
Equals
string str1 = "Hello";
string str2 = "hello";
bool areEqual = str1.Equals(str2); // false
Equals method checks the string variables and provides a boolean.
Compare
string str1 = "apple";
string str2 = "banana";
int result = string.Compare(str1, str2); // -1
The compare method returns an integer value that will tell you if the first string is more or less than the second variable.
CompareOrdinal
string str1 = "Apple";
string str2 = "apple";
int result = string.CompareOrdinal(str1, str2); // -32
Also compares the two strings, however uses ordinal (binary) comparison.
StartsWith
string text = "Hello, World!";
bool startsWithHello = text.StartsWith("Hello"); // true
StartsWith method will return a boolean that will say whether the string contains the provided data or not.
EndsWith
string text = "Hello, World!";
bool endsWithWorld = text.EndsWith("World!"); // true
Similar to the StartsWith method, however it will return a boolean that tells you whether or not the string ends with the provided data.
Contains
string text = "Hello, World!";
bool containsHello = text.Contains("Hello"); // true
The Contains method returns a boolean that tells you whether or not the string contains the provided data.
IndexOf
string text = "Hello, World!";
int index = text.IndexOf("World"); // 7
The IndexOf method will return an integer location of the subsring within the string. It will also return a -1 if the substring is not found within the string variable.
LastIndexOf
string text = "Hello, World!";
int lastIndex = text.LastIndexOf("o"); // 8
The LastIndexOf method will return an integer of the last occurrence of a specified substring within the string variable.
String Concatenation
In C#, you can add multiple strings together using the ‘+’ operator. I will create a blog post in the future about operators and expressions in the future so please follow the blog, my dev.to, or my GitHub.
string firstName = "Kyle";
string lastName = "Martin";
string fullName = firstName + " " + lastName;
// Or
string fullName = string.Concat(firstName, " ", lastName);
// Output : Kyle Martin
On my GitHub (link below) you will see a few practical uses of string concatenation.
That is it for now! If you made it this far, I really appreciate you reading my post. I know it was a long one. I really hope I was able to help you learn something new about C#. Thank you for reading!
GitHub – Thesnowmanndev (Kyle Martin) (github.com)
LinkedIn – Kyle Martin | LinkedIn
Ko-Fi (support my writing) – https://ko-fi.com/kylemartindevelops
Additional Resources:
C# Language reference – Reference Types
C# Language reference – The string type
C# Language reference – Ordinal vs culture-sensitive operations