Framework Fundamentals - String - Comparing Strings

  • In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison.
  • Equality comparison tests whether two instances are semantically the same.
  • Order comparison tests which of two (if any) instances comes first when arranging them in ascending or descending sequence.
  • For string Equality comparison, you can use the
    • == Operator
    • string.Equals() static method as will as instance method, this option is better because they allow you to specify options such as case-sentitvity/culture-sensitivity.
  • For string Order comparison, you can use the
    • CompareTo() instance method
    • string.Compare() static method
    • stirng.CompareOrdinal() static method
    • The return values of above said methods will be
      • 0 for equal
      • 1 if first value comes before second value
      • 2 if second value comes before first value
  •  

Framework Fundamentals - String

  • A C# string represents a sequence of Unicode Characters and it is defined in System namespace as System.string class.
  • String is immutable.
  • Construction of String
           //Method 1 - using Literals
            string s1 = "Sample string";
            //Method 2 - repeating sequence of characters with string Constructor
            string s2 = new string('*', 10); // **********
            //Method 3 - using Character array
            char[] charArray = "Hello".ToCharArray();
            string s3 = new string(charArray); // Hello
  • Null and empty strings
    • An empty string has a length of zero.
    • To create an empty string, you can use either a literal("") or the static string.Empty field;
    • Because strings are reference types, they can also be null.
    • The static string.IsNullOrEmpty method is a useful shortcut for testing whether a given string is either null or empty.
  • Accessing characters within a string
            //Method 1 - using Indexer
            string s1 = "Hello";
            char charAtIndexOne = s1[1]; // e

            //Method 2 - using foreach
            foreach (char item in s1)
            {
                Console.Write($"{item},"); // H,e,l,l,o,
            }
  • Searching within strings
    • string class provides instance method for searching within strings
    • Take Note: all string methods are case-sensitive and culture-sensitive.
            string s1 = "Hello Mr. X";
            Console.WriteLine(s1.Contains("x"));     //False - as it is smaller case
            Console.WriteLine(s1.StartsWith("HE"));  //False
            Console.WriteLine(s1.StartsWith("He"));  //True - as it is matches case
            Console.WriteLine(s1.EndsWith("x"));     //False -
            Console.WriteLine(s1.IndexOf("X"));      //10
            Console.WriteLine(s1.IndexOf("M",7));    // -1 , it searches from index 7 i.e character r in the string
                                                     // so it cannot find and returns  -1

            Console.WriteLine(s1.IndexOf("l"));      //2 searches from first character of the string i.e H
            Console.WriteLine(s1.LastIndexOf("l"));  //3 searches from last character of the string i.e X
            Console.WriteLine(s1.LastIndexOf("l", 1)); // -1 , it searches from index 1 i.e character e in the string

            Console.WriteLine(s1.IndexOfAny("abcde".ToCharArray())); // searches for either a or b or c or d or e
                                                                     //1 - found e in index 1
            Console.WriteLine(s1.LastIndexOfAny("abcde".ToCharArray())); // searches for either a or b or c or d or e
                                                                         //Search from last character
                                                                         //1 - found e in index 1

            Console.WriteLine(s1.IndexOfAny("Xabcde".ToCharArray())); // searches for either X or a or b or c or d or e
                                                                     //1 - found e in index 1
                                                                     //Searches from first character
            Console.WriteLine(s1.LastIndexOfAny("Xabcde".ToCharArray())); // searches for either a or b or c or d or e
                                                                         //Search from last character
                                                                         //10 - found e in index 1

Framework Fundamentals - Char

  • A C# char represents a single Unicode Character and it is defined in System namespace as System.char struct.
  • System.Char defines a range of static methods for working with characters, such as ToUpper(), ToLower(), and IsWhiteSpace(), please refer the table below for reference.
  • As you can refer from the last column of the table above, all the characters are categorized, if a character does not fall under any of categories given above, then it is considered as invalid character.
  • All these methods are culture-sensitive.
  • To check a character validity you can call static method char.GetUnicodeCategory(), if the result is UnicodeCategory.OtherNotAssigned, then character is invalid.
  • Example
            char a = 'a';
            Console.WriteLine(char.GetUnicodeCategory(a).ToString());  //LowercaseLetter
  • By default, a Char is 16 bits wide, and it is enough to represent all normal Unicode characters(called as Basic Multilingual Plane), Some special characters may need extra space, we will see about that in later posts.

When to use lock(this) and when not to use lock(this)

  • Before we see when to use and not use lock(this).
  • First let's see when to use locks
  • For explaining refer the below given code
    class JointAccount
    {
        int Balance = 10000;     
        public void WithDraw(int Amount)
        {
          
                if (Amount <= Balance)
                {
                    Console.WriteLine("Balance before withdraw: {0}", Balance);
                    Balance = Balance - Amount;
                    Console.WriteLine("Balance after withdraw: {0}", Balance);
                }
                else
                {
                    Console.WriteLine("Cannot withdraw, as amount exceeds balance");
                }          
        }
    }

    class Program
    {    
        static void Main(string[] args)
        {
            JointAccount jointAccount = new JointAccount(); //Joint Account of 10 members

            for (int i = 0; i < 10; i++)
            {                
                new Thread(() => jointAccount.WithDraw(10000)).Start();
            }
            Console.ReadLine();
        }
    }
  • It is Joint Account, so any one can have access to the account can withdraw amount from the Joint Account.
  • As per the above example Single Instance of JointAccount class is accessed by 10 threads almost at the same time
  • But anyhow, the balance shouldn't go negative, they cannot withdraw the money equal to the balance that they have in their account
  • But the above example will allow to violate the above said condition
  • Take Note: In a multi-threaded environment you cannot expect the same result all the times like single threaded, because of some times it may produce correct result, that doesn't mean it will always, so run your program multiple time to confirm you code is working fine.
  •  So the above code result may be like this
Balance before withdraw: 10000
Balance after withdraw: 0
Balance before withdraw: 10000
Balance after withdraw: -10000
Balance before withdraw: 10000
Balance after withdraw: -20000
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
  • So here, in this situation we need locking, because the code allows for balance to go negative
  • So now, that we all know a variable can be used as a locker, it should be of reference type.
  • And the locker variable should be private member of that class.
  • Why it should be a private member, why does it cannot be public?
  • A locker object should refer to the same object in memory, when it receives call from multiple threads
  •  So that it will be considered as all the threads are try to work on the same object(resource)
  • Now let's add the lock using a string object with public access modifier
class JointAccount
    {
        int Balance = 10000;
        public string locker = "";        
        public void WithDraw(int Amount)
        {
            lock (locker)
            {

                if (Amount <= Balance)
                {
                    Console.WriteLine("Balance before withdraw: {0}", Balance);
                    Balance = Balance - Amount;
                    Console.WriteLine("Balance after withdraw: {0}", Balance);
                }
                else
                {
                    Console.WriteLine("Cannot withdraw, as amount exceeds balance");
                }
            }
        }
    }
Balance before withdraw: 10000
Balance after withdraw: 0

Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
  • Now I have added the lock using a string object with access modifier public and it Works Fine. What is the issue?
  • let's modify the code, to change the locker reference before each thread request and see what happens.
class Program
    {    
        static void Main(string[] args)
        {
            JointAccount jointAccount = new JointAccount(); //Joint Account of 10 members

            for (int i = 0; i < 10; i++)
            {
                jointAccount.locker = i.ToString();
                new Thread(() => jointAccount.WithDraw(10000)).Start();
            }
            Console.ReadLine();
        }      
    }
Balance before withdraw: 10000
Balance before withdraw: 10000
Balance after withdraw: -10000
Balance after withdraw: 0

Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
  • After the changee, it may produce result like this, please read the Note In a multi-threaded environment you cannot expect the same result all the times like single threaded
  • There are chances, that the public member reference may change, that is why it is advisable to use private member.
  • Now lets come to the point When to use lock(this)?
  • In the prior example all the threads are working on a single instance of class. That is the Balance is commonly shared by all the threads. So here we can use lock(this) instead of having a separate locking object.
class JointAccount
    {
        int Balance = 10000;
        public void WithDraw(int Amount)
        {
            lock (this)
            {

                if (Amount <= Balance)
                {
                    Console.WriteLine("Balance before withdraw: {0}", Balance);
                    Balance = Balance - Amount;
                    Console.WriteLine("Balance after withdraw: {0}", Balance);
                }
                else
                {
                    Console.WriteLine("Cannot withdraw, as amount exceeds balance");
                }
            }
        }
        public void displayBalance()
        {
            if(Balance<0)
            Console.WriteLine("Final Balance {0}", Balance);
        }
    }

class Program
    {     
        static void Main(string[] args)
        {                      
                JointAccount jointAccount = new JointAccount(); //Joint Account of 10 members
                for (int i = 0; i < 10; i++)
                {                    
                    new Thread(() => jointAccount.WithDraw(10000)).Start();
                }                          
            Console.ReadLine();
        }       
    }

Balance before withdraw: 10000
Balance after withdraw: 0

Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
Cannot withdraw, as amount exceeds balance
  • When not to use lock(this) ?
  • Refer the example below
    class ThreadUnsafe {
        static int _val1 = 1, _val2 = 1;
        public void Go() {          
                if (_val2 != 0)
                    Console.WriteLine(_val1 / _val2);
                _val2 = 0;           
        }
    }
   class Program
    {     
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[20];
           for (int i = 0; i < 20; i++)
           {
                threads[i] = new Thread(() => new ThreadUnsafe().Go());                
            }
            for (int i = 0; i < 20; i++)
            {
                threads[i].Start();
            }
           Console.ReadLine();
        }       
    }
Answer is 1
Answer is 1
  • As you can see in the above example new instance of the class ThreadUnsafe is created with to call the Go method to update the static variable _val2.
  • But more than one thread updated the value of _val2. Even chances are there to get
    DivideByZeroException because one thread updated _val2 to 0 and other thread performing _val1 / _val2.
  •  So to make it thread safe, if updated this code with lock(this)
class ThreadUnsafe {
        static int _val1 = 1, _val2 = 1;      
        public void Go() {
            lock (this)
            {

                if (_val2 != 0)
                    Console.WriteLine("Answer is {0}", _val1 / _val2);
                _val2 = 0;
            }
        }
    }

Answer is 1
Answer is 1
Answer is 1
  • But still the code produces same kind of result
  • Why this happens?
  •  Ok, lets update the code with instance level locker instead of lock(this) and see what happens
class ThreadUnsafe {
        static int _val1 = 1, _val2 = 1;
        object locker = new object();
        public void Go() {
            lock (locker)
            {

                if (_val2 != 0)
                    Console.WriteLine("Answer is {0}", _val1 / _val2);
                _val2 = 0;
            }
        }
    }

Answer is 1
Answer is 1
Answer is 1 
  • From this we can understand one thing lock(this) and instance level locker is the same because of both work at the instance level, so each thread have its own object of locker/it is own object.
  • So here it should not be be instance level locker, it should be a class level locker
  • Now it works 
class ThreadUnsafe {
        static int _val1 = 1, _val2 = 1;
        static object locker = new object();
        public void Go() {
            lock (locker)
            {
                if (_val2 != 0)
                    Console.WriteLine("Answer is {0}", _val1 / _val2);
                _val2 = 0;
            }
        }
    }

Answer is 1

Framework Fundamentals - String - Comparing Strings

In comparing two values, the .NET Framework differentiates the concepts of equality comparison and order comparison . Equality compariso...