File Reading and Writing in C#

During program execution, data is saved and loaded from the main memory of the computer. Once program is closed, all the data is erased from the memory. What if you want your data to persist somewhere on your computer for future use? Suppose you have a point of sale system where you want to save your customers bio data. How would you do that?

You need a mechanism to read or write data to the file so that you can retrieve it in future. Usually a database is used for highly level related data storage. However, simple and plain data can also be stored in ordinary files. This article explains how you can read and write data to a text file.

Reading Data from Text File

Before executing the code, create a text file named “docs.txt” and add following text in it:

Crazy brown fox
Jumps over the lazy dog
and this is crazy..

Save the file, in the root of your “D:” directory and execute following code.

using System;
using System.IO;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            try {
                // Creating object of stream reader class
                using (StreamReader textreader = new StreamReader("d:/docs.txt")) {
                    string text;
                    // ReadLine function is used to read all lines in the text
                    while ((text = textreader.ReadLine()) != null)   {
                        Console.WriteLine(text);
                    }
                }
            }
            catch (Exception e) {
                // Display message if some issue occurs
                Console.WriteLine("Problem reading the file.");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, StreamReader class is being used to read the file. The path of the file to be read is passed to the constructor of the StreamReader class. The ReadLine method of the StreamReader class reads one line of text at a time and if text exists on the next line, it returns true.

Writing Text to a File

Writing text to the file is done via StreamWriter class. The WriteLine method of the class is used to write text, line by line to a text file. Have a look at the following example.

using System;
using System.IO;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            string[] statements = new string[] { "Hi, crazy wolf", "I know it makes no sense", "Still its cool." };
            using (StreamWriter textwriter = new StreamWriter("D:/sometext.txt")) {

                foreach (string statement in statements) {
                    textwriter.WriteLine(statement);
                }
            }

            // Reading the text which is written
            string text = "";
            using (StreamReader filereader = new StreamReader("D:/sometext.txt"))  {
                while ((text = filereader.ReadLine()) != null)  {
                    Console.WriteLine(text);
                }
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above program some random lines of text have been written to sometext.txt file which will be created at the root of the D: directory. Then again,the file that has been written is read via StreamReader object.

Dictionaries in C#

Dictionaries, like hashtable store data in the form of key-value pairs. However, unlike you need to define the type of those key and value pairs at the time of defining the dictionary. Dictionary collection belongs to System.Collections.Generic namespace. All the collections belonging to this namespace are type-safe which means that the type of the items in the dictionary are checked at run-time and if the type doesn’t match, the compiler gives error. This is unlike hashtable where you could store any object in place of key, as well as a value. Have a look at the following example to understand dictionaries.

using System;
using System.Collections.Generic;
using System.Threading;

namespace CSharpTutorials {
    class Tutorial  {
        static void Main() {
            Dictionary<int, string> stud_dic = new Dictionary<int, string>();
            // Adding Items in a Dictinary
            stud_dic.Add(20, "Johny");
            stud_dic.Add(15, "Liza");
            stud_dic.Add(11, "Sherry");
            stud_dic.Add(1, "Tommy");
            stud_dic.Add(21, "Johny");
            stud_dic.Add(12, "Ali");

            // Retrieving item using key
            Console.WriteLine("The student with roll number 11 is "+stud_dic[11]);

            // Checking if a dictionary contains key or value
            Console.WriteLine("If the key 20 exists in dictionary:" + stud_dic.ContainsKey(20));
            Console.WriteLine("If the value Johny exists in dictionary:" + stud_dic.ContainsValue("Johny"));

            // Clearing a Dictionary
            stud_dic.Clear();
            Console.ReadKey();
        }
    }
}

Download the code

In the above code a Dictionary object named stud_dic has been created. Notice the declaration of the Dictionary object, here key and value type has been specified, separated by comma within less than and greater than symbol. For stud_dic object, the key can only be of integer type while the value should be of string type. This Dictionary will not accept any other type as Key and value other than integer and string type respectively.

In stud_dic object, the key can be considered as the roll number while the value is the name of the student. You can access student name via his key as in the above example. Also, a key is always unique. For instance you cannot store 10 as key for two items in the stud_dic Dictionary object.

Multi-threaded Programming in C#

In the earliest days of programming, computing machines were single-core and processor could execute only single set of instructions at a time. Therefore, the program used to execute in a sequential manner where the instructions that came first in the code were executed first and so on. This programming paradigm is known as single threaded programming. A thread is basically smallest unit of execution.

Multi-threaded programming, on the other hand, depicts a programming phenomena where multiple program instructions run in parallel. Due to dual-core and quad-core processors, we are now able to implement multi-threaded programming in real sense.

In C#, threading is implemented via <Thread class which belongs to System.Threading namespace. The object of the Thread class takes a function as parameter. When the Start function is called on this Thread object, the function that is passed to the Thread object starts executing in Parallel. Have a look at the following example to grasp the concept.

using System;
using System.Threading;

namespace CSharpTutorials{
    class Tutorial {
        static void Main() {
            Thread newthread = new Thread(ThreadFunction);
            newthread.Start();// Function starts executing in parallel here.

            for (int i = 1; i <= 100; i = i + 2) {
                //function prints odd numbers less than 100;
                Console.Write(" "+i);
            }
            Console.ReadKey();
        }

        public static void ThreadFunction() {
            for (int i = 0; i <= 100; i = i + 2) {
                // function prints even numbers up to 100
                Console.Write(" "+i);
            }
            Console.ReadKey();
        }
    }
}

Download the code

In the above code, a function named ThreadFunction has been created which displays the even numbers from 0 to hundred. Inside the Main function a thread object newthread has been created and in the constructor of the object, the Thread function has been passed. Next, Start method has been called upon this object. At this point, two set of instructions start executing in parallel: One is the code in the main method and the other is the code inside the ThreadFunction.The main method starts printing the odd number while the ThreadFunction starts printing the even function. In the output, you will see odd and even numbers printed randomly. When the Main function gets the console, odd numbers will be printed and when ThreadFunction gets the console. even numbers shall be printed.

Stacks & Queues in C#

Stack and Queue collections in C# represent Stack and Queue data structures. A stack stores elements in the form of last in, first out. This means that the elements the item that is inserted at the end will be retrieved first. The term used for adding item into stack is called pushing while retrieving item is called popping.

A Queue class stores item on the basis of first in and first out principle. This means that the item which is inserted first is retrieved first while the item inserted at the end will be retrieved last. Adding item into the queue is called enqueue while while retrieving item from is called dequeue.

Have a look at Examples of Stack and Queue in C#

Stack

using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            Stack st = new Stack();

            //pushing elements in a stack
            st.Push("BMW");
            st.Push("Ford");
            st.Push("Toyota");
            st.Push("Honda");
            st.Push("Suzuki");

            // popping elements from stack

            Console.WriteLine(st.Pop());
            Console.WriteLine(st.Pop());
            Console.WriteLine(st.Pop());

            //Clearing a stack
            st.Clear();

            Console.ReadKey();
        } 
    }
}

Download the code

In the above code a Stack object st has been created and some car names have been added to it. Now, if Pop method is called on the Stack object, the name of the cars will be displayed in their reverse order of insertion. This ascertains the fact that Stack class in C# follows last-in,first-out principle.

C# Queue

using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            Queue qu = new Queue();

            //en-queueing items in the queue
            qu.Enqueue("BMW");
            qu.Enqueue("Ford");
            qu.Enqueue("Toyota");
            qu.Enqueue("Honda");
            qu.Enqueue("Suzuki");

            // de-queueing items from the queue
            Console.WriteLine(qu.Dequeue());
            Console.WriteLine(qu.Dequeue());
            Console.WriteLine(qu.Dequeue());

            //Clearing a queue
            qu.Clear();
            Console.ReadKey();
        } 
    }
}

Download the code

In the above code, names of different cars are stored in Queue object via Enqueue method. Now if the objects are retrieved from queue via Dequeue methods, they will be returned in the ascending order of insertion. This proves that Queue class in C# follows first-in, first-out principle.

Hashtable and SortedList in C#

Hashtables and SortedLists are two of the most commonly used collections in C#. Both of them belong to System.Collections namespace. Let us see what we can do with these collections.

Hashtable

A Hashtable stores collection of data in the form of key-value pair. This means that each item within the Hashtable consists of two parts: A key, and a value corresponding to that particular key. The items are accessed by passing key to the Hashtable variable. Have a look at the following example.

using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            // Creating a Hashtable
            Hashtable sampletable = new Hashtable();

            // Adding elements to hashtable 
            sampletable.Add("Jacob","12335");
            sampletable.Add("Stacy", "43434");
            sampletable.Add("Kelly", "56332");
            sampletable.Add("Mike", "23413");
            sampletable.Add("Carla", "83578");
            sampletable.Add("Vinset", "67393");

            // Printing phone number of kelly using key.
            Console.WriteLine("Phone number of Kelly is:" + sampletable["Kelly"]);

            //Checking if Mike exists in the hashtable
            Console.WriteLine("If Mike exists?:" + sampletable.ContainsKey("Mike"));

            // Removing Element from hashtable
            sampletable.Remove("Carla");
            Console.ReadKey();
        } 
    }
}

Download the code

In the above example a Hashtable named sampletable has been declared. Some items have been added in this hashtable in the form of key-value pairs via add function. The key refers to name of some random person, while value refers to imaginary phone number. You can have any key-value pair that you like. Now to access number of some person, simply use its key and pass it to the hashtable as index. Above code also explains the usage of ContainsKey and Remove methods.

SortedList

SortedList in C# is a collection that contains properties of both an ArrayList class and a Hashtable. Elements within a SortedList are stored in the form of Key-value pairs and are sorted by default on the basis of key. The elements can be accessed both by index and by key. Have a look at this example.

using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {

            SortedList sortedlist = new SortedList();

            sortedlist.Add("John", "76489");
            sortedlist.Add("Dave", "67849");
            sortedlist.Add("Mike", "68699");
            sortedlist.Add("Sara", "76233");
            sortedlist.Add("Mark", "56739");

            //printing SortedList elements
            foreach(var a in sortedlist.Keys)  Console.WriteLine(a);

            //Accessing elements via index
            Console.WriteLine("Value of Dave is:" + sortedlist.GetByIndex(0));

            //Accessing elements via key
            Console.WriteLine("Value of Dave is:" + sortedlist["Dave"]);

            Console.ReadKey();
        } 
    }
}

Download the code

In the above code a SortedList has been defined and iterated. The iterated collection will display the items i alphabetical order which means that SortedList is sorted by default. Next, a value in the list is accessed first via index and then via key.

Reflections in C#

One of the most useful properties of C# language is its ability to get information about the assembly, classes and members variables at run time. This functionality is achieved via reflection objects.

Reflection classes belong to system.Reflection namespace and provide several functionalities to get useful information from the .NET managed code at run time. Reflection classes also let developers modify the characteristics of types and assemblies on the go.

Reflections are also used for defining new types and members at run time. In the following example, the method name is accessed by the code within the method. Also, the name of the currently executing assembly is being accessed within that method. Finally the type of object is being accessed within the main method. Have a look at this example.

using System;
using System.Reflection;
namespace CSharpTutorials {

    public class Vehicle {

        public void VehicleMessage() {
            // Code to get name of the method in which code is
            string methodname = MethodBase.GetCurrentMethod().Name;
            Console.WriteLine("This code is within "+methodname+" method");


            // code to get object of current assembly name
            string assemblyname = Assembly.GetExecutingAssembly().GetName().Name;
            Console.WriteLine("This code is within " + assemblyname + " assembly");
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            Vehicle veh = new Vehicle();
            veh.VehicleMessage();
            Type typeofobject = veh.GetType();
            Console.WriteLine(typeofobject.Name);
            Console.ReadKey();
        }
    }
}

Download the code

The first thing to notice in the above code is the use of System.Reflection namespace via using. This statement prevents developers from writing fully qualified type names. Next, a class named Vehicle has been defined and in this class, a method named VehicleMessage has been created. Inside this method, Reflection type MethodBase is being used to get the name of the current method. Next, Assembly class is being used to get the name of the currently executing assembly via the GetExecutingAssembly method.

Finally, To get the name of the class of the object the GetType method is called on the object inside the Main method.

Properties in C#

Properties are similar to member variables in C#, however they differ in terms that they provide controlled access to member variables. Encapsulation is one of the pillars of object oriented programming and properties help implement encapsulation of member variables in C#. Consider a scenario where you want to store a value of 100 in an integer variable if the value is greater than 50, otherwise 0 should be stored in that particular variable. In such cases, instead of using a method, you can achieve the same functionality with the help of properties.

Properties have accessors in the form of get and set. The get accessor is used to return the value of the member field encapsulated by the property and the set accessor is used to set the value of the member field. Have a look at the following example to understand this concept.

using System;

namespace CSharpTutorials {

    public class Vehicle {

        private string vehicle_name;
        private int vehicle_price;
        private int vehicle_model;

        public string Name {
            get {
                return vehicle_name;
            }
            set {
                vehicle_name = value;
            }
        }

        public int Price {
            get {
                return vehicle_price;
            }
            set {
                if (value > 50)  vehicle_price = 100;
                else  vehicle_price = 0;
            }
        }
		
        public int Model {
            get  {return vehicle_model;}
            set  {vehicle_model = value;}
        }
    }

    class Tutorial {
        static void Main(string[] args) {

            Vehicle vehicle = new Vehicle();
            vehicle.Price = 55;

            vehicle.Name = "BMW";
            vehicle.Model = 2005;
            Console.WriteLine(vehicle.Price);

            Console.ReadKey();
        }
    }
}

Download the code

In the above Example, a class named Vehicle has been defined that contains three member variables, vehicle_name, vehicle_price and vehicle_model. The class also contains three properties Price, Name and Model which are used for encapsulating vehicle_price, vehicle_name and vehicle_model,respectively.

A check has been implemented for the set accessor of the Price property which checks if the value being assigned to vehicle_price member variable is less than 50? If it is less than 50, 0 will be assigned to vehicle_price member, if the value is greater than 49, 100 will be assigned to it. In the Main method, 55 is being assigned to Price property. So now if the value vehicle_price variable is printed on screen, it will display 100.

Events in C#

During program execution, user interact with the program by clicking different screen areas, pressing different keys and hovering mouse at different places. All of these user actions are basically events. Events are also raised by system itself in the form of notifications and interrupts. This article explains how these events are handled and how certain piece of code can be executed as a result of these events.

Events in C# follow a publisher-subscriber model. Publisher is basically a class that contains the event declaration and corresponding delegate which contains referent to the event handler. Subscriber is the class which contains event handler which is nothing but a method which is executed when a certain event occurs. Sometimes, a publisher and subscriber can be same class. Have a look at the following code snippet to understand this concept.

using System;
namespace CSharpTutorials{

    public delegate void delegateevent();
    public class EventPublisher {

        public static event delegateevent eventtofire;
        EventSubscriber es = new EventSubscriber();
        public void BindEvent()  {
            // Bind the event to evenhandlers
            eventtofire += new delegateevent(es.DisplayMessage);
            eventtofire += new delegateevent(es.DisplayMessage2);
        }
        public void InvokeEvent()  {
            //invoke the event
            eventtofire.Invoke();
        }
    }

    public class EventSubscriber {

        public void DisplayMessage()  {
            Console.WriteLine("An event has been fired");
        }
        public void DisplayMessage2() {
            Console.WriteLine("Another event has been fired");
        }
    }

    class Tutorial {

        static void Main() {
            EventPublisher pub = new EventPublisher();

            pub.BindEvent();
            pub.InvokeEvent();
            Console.ReadKey();
        }
    }
}

Download the code

In the above code EventPublisher and EventSubscriber classes have been created. EventPublisher class contains delegate which should match the syntax of the event handler that will be triggered once an event is called. The event itself should also be of the delegate type. In the EventSubscriber class, we have two methods DisplayMessage1, and DisplayMessage2. We want that when our event is triggered, these two event handlers should be called.

To do so, we need to bind the event with the handler, this is done by using “+=” operator where event is on the left side and the event handlers are passed to the delegate type object. This way, you can bind multiple event handlers with one event. Finally, to invoke the event, the Invoke function is called on the object which triggers the event.s

Delegates in C#

In C and C++, you would have heard of pointer which point to some variable or function. Delegate in C# is a similar concept. They are reference type variables that hold the reference to some function. Delegates in C# are particularly used for implements callbacks and events which are backbone of GUI based programming.

To create a delegate, keyword delegate is used followed by the return type of the function that delegate will refer, then name of the delegate and the parameters. The parameters should be same and in the same order as is the case with the function that will be referenced by the delegate. Havea look at the following example to understand this concept.

using System;

namespace CSharpTutorials {
    // Delegate is created here
    public delegate int PerformMaths(int num1,int num2);

    public class MathematicsOperations {
        public int AddNum(int a, int b)  {
            return a + b;

        }
        public int SubNum(int a, int b) {
            return a - b;
        }
        public int MulNum(int a, int b) {
            return a * b;
        }

        public int DivNum(int a, int b){
            return a / b;
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            
            MathematicsOperations mo = new MathematicsOperations();

            // Delegate variable declaration and referencing the function to call
            PerformMaths mathfunction = new PerformMaths(mo.AddNum);
            // making the call to function by passing parameters.
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.SubNum);
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.MulNum);
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.DivNum);
            Console.WriteLine(mathfunction(20, 10));

            Console.ReadKey();
        }
    }
}

Download the code

In the above example a delegate PerformMaths has been declared at the top. This delegate has a return type of int and receives two integer type parameters. This means that this delegate can point to any method that has a return type of integer and accepts two integer type variable. Next a class MathematicsOperations has been defined. This class contains four methods which receive two integer type arguments, perform some mathematical operation on them and return the result in integer form. This means that our delegate can refer to all of these methods.

Our delegate type variable mathfunction can refer to these methods by passing these functions (without parameter) to the delegate constructor. Next the fucntion can be called by passing parameters to the delegate variable itself.

ArrayList C# Class

ArrayList C# is a powerful, resizeable Array

An ArrayList C# class can be considered as a more advanced form of simple array with much more advanced features. A simple array is immutable, which means that once created it cannot be resized and elements can neither be removed nor added. C# ArrayList object, however is dynamic and allows developers to resize the array by adding additional items or by removing existing items. In addition, an ArrayList class also provides advanced functionalities like searching and sorting etc.

Have a look at the following example to see how ArrayList class is created and how different functionalities can be achieved through it.

using System;
using System.Collections;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            
            // Creating an ArrayList
            ArrayList samplearray = new ArrayList();

            // Adding Elements to ArrayList class
            samplearray.Add(10);
            samplearray.Add(13);
            samplearray.Add(40);
            samplearray.Add(2);
            samplearray.Add(32);
            samplearray.Add(51);
            samplearray.Add(45);

            //Sorting the ArrayList

            samplearray.Sort();

            //Iterating through sorted ArrayList
            foreach (var val in samplearray) {
                Console.Write(val + " ");
            }

            // finding element at a particular index
            var value = samplearray[2];
            Console.WriteLine(value);

            // Removing element at some index
            samplearray.RemoveAt(2);

            //Iterating through sorted ArrayList again
            foreach (var val in samplearray) {
                Console.Write(val + " ");
            }

            // Reversing an array
            samplearray.Reverse();
            Console.WriteLine("\nReversed Array");

            //Iterating through sorted ArrayList again
            foreach (var val in samplearray) {
                Console.Write(val + " ");
            }
            // clearing an array
            samplearray.Clear();
            Console.ReadKey();
        }
    }
}

Download the code

Code Explanation

In the above code, we stored some random integers in the ArrayList named samplearray. C# ArrayList items are of object type. This means  you can store values of different types in one ArrayList object. The samplearray has been sorted using Sort() function. Values stored in the samplearray have been displayed on the screen using foreach loop.

Also the code demonstrates how an item can be accessed via index, how to remove an item from a specific index. In addition, Reverse() function has been used to reverse the contents of the array and then these contents have been displayed on the screen. Using Insert() function you can insert an element at a specified index in the C# ArrayList. Finally, samplearray object is cleared via Clear() function.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .