In the previous discussion we talked about various topic like Threading, types of threading like Synchronous and Asynchronous, Delegates, Multicast delegates, Events, Broadcasting, difference between multicast delegates & events.

Now in this part of discussion we will discuss further about some other fundamental concepts and their relations and uses.

So first of all we start with, what is stack? What is heap?

Stack:

Here we first of all understand the meaning of Stack. The meaning of Stack says that it is a pile of objects which is neatly arranged.

Similarly the same understanding of Stack can be applied to the .NET framework. In .NET framework it says that, Stack is a memory type in an application.

It means that in a normal application, when we define some data that data consumes a small piece of memory and gets stored in this memory type. Now as the memory type is Stack the data stored in this type is also neatly piled up and arranged. And depending on the application this data is then consumed in any order such as First in First out (FIFO) or First in Last out (FILO).

Now this Stack memory stores all the regular datatypes in .NET framework such as int, double, Boolean, etc. We take a simple sample code to understand this.

public void Method()

{

int i = 4;

inty = 2;

}

Now here integer datatype i is defined and its value is mentioned. Also in the same way another integer datatype y is defined and value is provided. Now assume a box which is open from the top, from where we put things inside. Now normally when we put things in the box we tend to put the first item in the bottom and then the next few items above the first item forming a stack one above the other. In the similar way first i = 4 is stored and then on top of it y = 2 is stored.

a1

In this way Stack works.

Heap:

As we discussed about Stack we now discuss another concept somewhat similar to Stack. It is called as Heap. Now first understanding the general meaning of Heap which says that it is a collection of objects put on top of each other in a haphazard & unorganized manner. It somewhat sounds like the Stack only difference is that stack is an organized pile of objects whereas heap is an unorganized pile of objects.

But here in .NET framework Heap is also a memory type in an application like Stack and it also does the same function like stack where a data is defined and that data is consumed and store in this memory type. Here the Heap only stores two datatypes such as string and objects.

We understand this Heap concept with sample code.

public void Method()

{

int i = 4;

int y = 2;

object o = null;

}

Here as we know that the integer datatype i and y are stored in Stack as they are normal or simple datatypes. Now in the 3rd line of code a datatype object is defined and now that object is store in heap. Here value of object o in is null, that is o = null.

Now as we see that when the code is ended with closed curly bracket }, it means that after the code is finished the pieces of memory in the stack is reclaimed while the pieces of memory in the heap stays there so that the garbage collector can reclaim it.

So in this way the memory types in an application like Stack & Heap works.

Now after getting to know these concepts we move on to the next topics which are widely related to these Stack and Heap. We will discuss about Value Types and Reference Types.

In the previous discussions (part 2) we discussed about the value types and reference types but not in that much detail.

Value Types:

As the name itself says that value types are that datatypes which stores only the value of the data. We can also say that the value types have actual data.In this the data type stores the copy of the value. It means when a datatype value is assigned to another datatype value, it will create a totally new copy. And when that new copy of datatype’s value is changed it will not change the original value.

Now we know that reading the above 2 lines will not make the concept of “datatype stores the copy of value” easier, while reading it looks a bit complicated but it is very easier to understand. Let us take a sample code to understand this.

public void Method()

{

int i = 2;

int y = i ;

}

Here we are defining the integer datatype i = 2, and then in the next line of code we are defining another integer datatype of y =i. Now when the code is executed first the value of i =2 is stored in the stack and then y =2 is stored. Here we have assignedtheidatatype to y datatype and therefore a total altogether new copy of i datatype is created that is y=2. Now this y=2 is a new copy and if we then change the value of y=2 to y=4, the value of i will be i=2 and it will not change because though we have assigned the value of i to the datatype value of y, the y datatype has created a new copy. And this new copy enables the y datatype to change without making any changes to i datatype. In short if we change one the other doesn’t change.

Also the value types are always stored in the Stack because the value types contain simple & normal datatypes such as int, double, Boolean, etc.

Reference Types:

Here also as the name says reference types are used for referring the value of the datatype. They act as a pointer to point towards actual data. Also we can say that the reference types stores the address of the value.

Now in reference types when we create two objects and assign the value of one object to other. It happens that both the objects point towards the same memory location. So if we try to change the value of one object the value of other object also changes.

To understand this we take a sample code.

public void Method()

{
    Cls1 obj = new cls1();

    Cls1 obj1 = obj ;
}

Here we have created a class called cls1 and then we have created two objects such as obj& obj1. Now we have assigned the value of obj1 to obj i.e. obj1=obj which is the second line of code. Now these two object obj& obj1 point towards the same memory location in the Heap. So if we try to change the value of obj1 the value of obj also changes and if we change obj then obj1 will also change. This happens because they both point towards same memory location, not like the value types where totally a new copy is created and changing one does not changes other. This is how reference types work.

Also Reference types are always store in Heap because the reference type contains datatypes such as string & objects. Objects are usually reference types.

Now as we have discussed about value types and reference types, there is another important topic which is linked with all the above topics we have discussed.

Boxing:

This boxing concept totally uses the value types and reference types. To define it in proper technical words we say that when the value type is moved to a reference type it is known as Boxing.

To understand this we take a sample code.

int i = 1;

objectobj = i;

Here inti  is a value type and object obj is a reference type. In this two lines of code we are moving the value type int i =1 to the reference type object obj = i. This is how Boxing works.

Unboxing:

As the name itself says it is totally the opposite of how the Boxing works. Again defining in proper technical words, we can say that when a reference type is moved to value type it is known as Unboxing.

To understand this we take a sample code, we continue with the code from above,

int i = 1;

objectobj = i;

int j = (int) obj;

Here in the last line of code we see that we have created a new datatypeint j and we are moving the value of object datatype to the int j datatype i.e. we are moving the reference type to value type. In this way Unboxing works

Now the question arises how to avoid Boxing & Unboxing?

Because in the process of Boxing & Unboxing it consumes a lot of memory as data jumps from stack memory to heap memory. As it is a memory consuming process the performance is affected.

So First of all it is difficult to avoid Boxing & Unboxing because most of the time we will be moving data from UI objects like textboxes, etc. to business objects and vice versa which will need the use of Boxing & Unboxing. So it is necessary to use Boxing & Unboxing. But we have to try to make sure that we make use of Boxing & Unboxing as less as possible by making a good practice of it.

So as we have learnt about the Boxing & Unboxing concept along with other concepts related to it, we now move further to a new topic of discussion.

Regex:

Regex is also called as Regular Expression. Now defining it in proper technical words we can say that Regex or Regular Expressions helps us to describe complex patterns in the text and once we describe it we can search, replace, extract and also modify text data.

Now to properly understand this regex we consider a few examples such as:

05/06/2016    (MM DD YYYY)

xyz@gmail.com

www.xyz123.com

Now in the above examples we see that each text data has its own format or its own pattern which is followed while writing the text data. Above the first example is a date which is in mm ddyyyy pattern.

Second example is an email id where it follows a certain pattern in which there is a name followed by @, then the domain name like gmail, yahoo, etc. and then .com, .in, etc.

Third example is of a website where it follows a certain pattern where the website starts with www then a dot comes then the domain name comes and then the .com, .in, .org, etc.

So every text data type has a pattern and regular expression helps us to describe or define these patterns. After defining it we can then validate the data, search, modify, etc.

Now to understand regex or regular expression in the beginning it is very difficult but here we will see what syntaxes are used to define a regular expression which will make our understanding easier.

So there are 3 types of main syntaxes which help us to define or describe a regex. They are as follows:

B: Brackets

C: Carrot Sign

D: DollarSign

  • In Brackets we use all the 3 kinds of brackets such as “[“Square bracket, “{“Curly brackets and “(“Round brackets. Square brackets are used to specify the characters which are to be matched. Curly brackets are used to specify how many characters. Round brackets are used for grouping.
  • Carrot sign “^” is used to specify start of a regular expression.
  • Dollar sign “$” is used to specify end of a regular expression.

Now generally a regular expression looks like this:

^ [a-z]{1,15}.(1,2) $

Now we will see how the different syntaxes work for making a regular expression.

First of all we know that Carrot sign “^” is used to specify that the regular expression starts from there and Dollar sign “$” is used to specify that the regular expression ends here.

Secondly we see how different types of brackets are used. Now the square bracket is used to make sure that whatever characters are put in that bracket must match the text data. For e.g. if we put the characters in square bracket such as [a-h], the text data should contain the data in the range of a-h. Any data outside that range will make text data invalid. Now if we want that the text data should contain both small & capital letters we have to put the characters in the brackets as [a-zA-Z]. Now if we want to also put number in text data we have to put in bracket as [a-zA-Z0-9]. Therefore our text data will look like abYZ123.

Now the Curly brackets are used to make sure how many characters should be there in the text data. For e.g. if we put the characters in our curly brackets as             [a-zA-Z0-9]{5}, then the text data should contain the data up to only 5 characters so it will be as abZ12. If we put {1} in the curly bracket it will look like either a or A or 1. Here if we do not put anything it will show invalid data as the number of characters in the bracket is only 1. Now if we put the characters in the curly bracket defining the minimum & maximum limit it will look like as [a-zA-Z0-9] {0,9}. Here the minimum number of characters is 0 and maximum is 9. So our text data will look like abcXYZ123. If we put the limits as {2,7} then it will specify that minimum number of characters are 2 an maximum are 7.

Now the Round Brackets are used for grouping the data. We often see that any email id or a website contains a .com, .in, .org, etc. in the end. So to write domain extensions in the regular expression pattern we use round brackets. It can be written as (.com|.in|.org|.net). “|” this symbol is the OR condition. So if we want to write the whole expression it can be written as [a-zA-Z0-9]{0,9}.(com|org|in) so it will look like abcXYZ123.com or abcXYZ123.org or abcXYZ123.in

In this way all the syntaxes are used for defining the regular expressions.

Now we take two examples of validations which will help us understand the concept of Regular Exprsssion.

  • Simple Validation for website’s URL:

^www.[a-zA-Z0-9]{0,9}.(com|org|in|net)$   its text data will look like

www.Csharp123.com  or www.Csharp123.org  or www.Csharp123.in

  • Simple Validation for email id:

^[a-zA-z0-9]{0,9}@[a-zA-z]{0,9}.(com|org)$   its text data will look like

Csharp123@Training.com  orCsharp123@Training.org

Now moving on to the next topic which is an important one.

C# Indexer:

Now if we consider the general meaning of indexer, we can say that it is used to simplify the collection of data. In the same way the Indexer in C# works. It can be technically defined as “Indexer helps us to simplify the way we access a collection from a class”.

As we know that every book has an index and with the help of that index we can simply pick up the chapter we want and also the specific topic in that chapter. This happened because the index simply helped us to access the collection of chapters from a book.

In the same way the indexer works in C#. Now many a times it happens that in the programming code we have several classes and these classes have aggregated or combined collection. Suppose we have a customer class and address class and it happens that one customer has more than one address. So now we want to fetch the addresses collection by “pin code” and “phone number”. From the client side the code looks like

customer Customers = new Customer ();

Customers.getAddress (1001);

Customers.getAddress (“9030”);

Here the user sees get address and then the user puts the data. But now if we don’t want the users to even see the get address, instead the user directly put the query of pin code or phone number and access the collection. And therefore to make the code even simpler we use indexer. While using indexer we use “this” keyword.

To understand indexer and its implementation we see a sample code below.

public class Customer


{


 Private List<Address> Addresses = new List<Address> ();


public Address this [intPincode]

              {

                 Get

                  {

Foreach (Address o in Addresses)

                   {

             If (o.Pincode == PinCode)

                      {
return o ;
                          }

                      }

return null;

                      }

                  }

publicAddress this [string PhoneNumber]

         {

         Get

                 {

Foreach (Address o in Addresses)

                {

                 If (o.MobileNumber == PhoneNumber)

 {

return o ;

                                       }
                                }
return null;

              }

       }

}

Here in this code we see how the “this” keyword is used as an indexer. One more important thing to remember in the indexer is that indexers are properties so we have to define the set and the get. So now here we can see

Customer Customers = new Customer ();

Address o = Customers [1001];

o = Customers [“9030”]

Here the Customer class itself is indexed. So as we write the Class name as Customer and put a square bracket we can see that by directly putting the phone number or the pin code we can access the address easily.

So in short if we summarize we can say that Indexer helps us to access contained collection or aggregated collection within a class by using simple interface. It is a syntactic sugar.

 

 

Advertisements