Home Classroom C# .NET

4173

After a long break from my first post, I would like to explain in this post how to get public events from a public Facebook page into an ASP.net MVC application without having to login to Facebook. I hope having a basic understanding about Asp.Net MVC will help you to understand this article quite well.

First let’s create an ASP.net MVC application in Visual Studio (I am using 2012 version in this post), go to File=> new=>project and you will be able to see the list of project Templates available, I will use “Asp.net MVC 3 Web Application” template under “web” category (Figure 1). Give a Name and the location for your application and click ok.

NewProject

 Figure 1

Then you will be prompted to select one of the sub templates available under Asp.net MVC3

subTemplate

Figure 2

Select “Internet Application” template and set the “view engine” as “Razor” (Figure 2) and click ok. After a while you will get a fresh MVC application.

FreshMVC

 Figure 3

Now hit F5 to start debugging on the newly created application

welcometoASP

 Figure 4

If you can see the screen on Figure 4 we are good to proceed further  :)

In order to get the Events from a Facebook page, you must possess a Facebook Application, since the app token of that application will be used to authorize your request. Go to https://developers.facebook.com/  and go to the “Apps” section(Figure 5)

Apps

Figure 5

From there click “Create New App” and create a new Facebook Application (Figure 6).

CreateNewApp

Figure 6

And make sure its “Sandbox Mode” is disabled under “Basic Info” heading.

sandbox

Figure 7

Then we need to get the “App token” of our newly created application, go to tools section from the menu bar and from the set of tools in the right side of the page select “Access Token tool” (Figure 8)

AccessTokenTool

Figure 8

From there you can get the “App Token” for the newly created application (Figure 9)

AppToken

Figure 9

Next, in order to refer to our public Facebook page we need its Facebook Id. The Facebook Id of the page can be taken easily by providing the url of the page to this website (Figure 10)

http://findmyfacebookid.com/

FacebookIdFinderFigure 10

Now we have all the components require to make the request for the events. Use the following format to make the request

https://graph.facebook.com/{0}/events?access_token={1}&limit={2}&after=1&fields=owner,name,description,cover,id

Replace the content as follows

{0}= Id of your Facebook Page

{1}= App Token of your application

{2}= Maximum number of events to be received

Under “fields” parameter you can specify the required details about the event, using the phrases in the Facebook Graph API

https://developers.facebook.com/docs/graph-api/reference/event/

ex:

https://graph.facebook.com/566125203483000/events?access_token=1459623080931717|QlAXMsfKQ0YO9i3iZwFsyb5cGbQ&limit=2&after=1&fields=owner,name,description,cover,id

If we call this url inside a browser we will receive a JSON result like this ( Figure 11).

JSONResult

Figure 11

Now we have received the Data we need, as the next step let’s see how this data can be formatted and displayed inside our MVC application.

First we have to prepare our model, a JSON string like this can be easily converted into a collection of C# object using “Newtonsoft.Json” Library. In order to install this package right click on the “FacebookEventApplication” solution in “Solution Explorer” and go to “Manage Nuget Packages”. In the package manager window select the “online” category and search for “Newtonsoft” in the search box. Then select the result “Json.Net” and click “install”.

Nuget

Figure 12

After installing Newtonsoft JSON, let’s write our model class. Write click on the project go to add=> class. Select “C# class” template and give a name for your model class (Figure 13)

New class

Figure 13

First add a using statement for Newtonsoft,

using Newtonsoft.Json;

Then create properties which correspond to the fields in the JSON result we got, markup each property with the respective name in the JSON string (Figure 14). A Dictionary property has been used for “CoverInformation” since the “cover” field in the JSON result has some sub fields.

Newmodel

Figure 14

Now we are ready to make the call for the Json result inside the Index method of our Home Controller.

newhome

Figure 15

First we should create a WebClient object(line 18).  The WebClient class is used to send or receive data from a URI. Then the url which we used in Figure 11 to get JSON data is defined as downloadUrl. Then we need to create a URI object, URI class is used to represent a URI. And the URIKIND is defined as absolute since we are giving an absolute address. After creating the URI we can start downloading the events details by calling the DownloadString method in the myWebClient object while passing the URI as an argument. If we observe the JSON result we receive in Figure 11, we can see that the JSON object we receive has several properties and the property which we need is the Array called “data”. So in order to separate that array easily, first let’s create a JObject from the “downloadedJsonResult” which is a string. Then in line 30 we have selected the “data” property of that object and assigned it to a JArray. Both JObject and JArray are classes provided by NewtonSoft JSON library. The next step would be deserializing this JSON array into a list of “FacebookEvent” objects. It is done in line 32. After getting the “listOfFacebookEvents” list we pass this list into our view.

Next we have to define a view to display this data. Since we are using the Index Action Method in the HomeController which was already in the default template, a view corresponding to this action method is already available.  Right click on the “Index” word in the Index action (Figure 16)  and Select Go To View

gotoview

Figure 16

Add the following Code to the view Body

ViewContent

Figure 17

Here using a foreach loop we iterate through the list of FacebookEvents which we passed into the view at the controller. We use Html.Display to generate a label to display the name of the each event. And after that we have to use an anchor tag which allows the users to browse to that particular event on Facebook. The “href” property of the anchor tag has been assigned with the url of the particular Facebook event. Finally we have added an image tag to display the cover photo of the event. The CoverInformation property we defined in our FacbookEvent class is a dictionary, we need to take the “source” element of that dictionary by passing “source” into square brackets.

Then we can press F5 and see the functionality of our MVC application

eventDisplay

Figure 18

We can click on the “Go To Event” link of a particular event and navigate into that event on Facebook.

SampleEventTwo

Figure 19

I hope you have understood my explanation on getting Facebook Events details into an ASP.net MVC application without logging to Facebook, and I hope it will be useful for you all. Please express your views, questions on this post since they help me a lot to make my future posts much beneficial for you all !. See you again soon with another article.

Happy Coding!

32821

Hello everyone! Welcome to my very first article on diGit. In this article, we will look at how to perform Optical Character Recognition (OCR) in C#.

For this we will use Puma.net library which makes our task much easier. You can download it from CodePlex, which hosts Open Source Projects.

After downloading, run the downloaded file and install it in your machine. I will illustrate this to you by using a small WPF application. After installing Puma .Net go to the “Assemblies” folder in the installation location. Usually they are in C:\Program Files (x86)\Puma.NET\Assemblies (in a 64-bit machine).

You should see three DLL(Dynamic-Link Library or .dll) files as follows.

Figure (a)

Figure (a)

Next go to the properties of the”COM Server” folder which resides at C:\Program Files (x86)\Puma.NET

Go to the security tab and click edit.

Figure (b)

Figure (b)

And make sure you have given full control for the current user.

Next open Visual Studio (I am using 2012 version) and go to File=> new=> project

Figure (c)

Figure (c)

Under “Windows” category choose “WPF Application” and under “Name” give a name for your application and click  OK.

 Right click on your project and select “Add Reference” and go to “Browse” section.

Figure (d)

Figure (d)

Click on “Browse” and locate the” Puma.Net.dll” file which resides in C:\Program Files (x86)\Puma.NET\Assemblies  (in 64-bit machine) and click OK.

Right click on your project  and select “Rebuild”.  After rebuild completes right click on the project again and select “open folder in file explorer”. Go to Bin => Debug and you must  have  “Puma.Net.dll” , and “puma.interop.dll” files inside that folder. From the location in figure (a) you must copy “dibapi.dll” file into this location. Now your Debug folder must have the following content:

Figure (e)

Figure (e)

Now go to “MainWindow.xaml ” in our WPF Application and create an interface like the following by simply using the items in the toolbox.

Figure (f)

Figure (f)

The first  File Selector is used to select the source image file. We can get the output of the OCR as a string or we can directly write it into a file. The second file selector is used to select the destination file for the second scenario.

So now let’s look at the code written in event handlers.

 First let’s consider the click event of the “Select Source” button.

Figure (g)
Figure (g)

Here I have created an object from the “OpenFileDialog” class which helps us to locate the source image that we use to read. The “ShowDialog()” method in this class will open a file chooser window and it returns a boolean value which indicates whether a file has been selected or not. And I have taken the path of the selected file using the “FileName” property and set it into the first TextBox in Figure (f).

Now let’s consider the actions caused by the click event of the “Read to screen” button

Figure (h)
Figure (h)

Here we are creating an object from the “PumaPage” class and we have to pass the path of the source image file which we got in the previous step into the constructor of this object. And then we can set the output format we want (line 54), and set the language which is used in the source image(line 55). Using the “RecongnizeToString()” method we can take the output of the reading into a string. I have applied that string into a “TextBlock”  in our MainPage.xaml. Finally I have called the “Dispose()” method so this PumaPage object will be disposed allowing another PumaPage object to get hold of the source image file.

Here is the code under “SelectDestination” button

Figure (i)
Figure (i)

This has a similar functionality as the “Select Source” button in Figure (g) and it will let us select the destination file where we would like to save the output if we plan to save it in a file. And that path is assigned to the Second TextBox in the MainWindow.xaml page. 

Click event in the “Read to File” button

Figure (j)
Figure (j)

The functionality of this event is similar to “read to screen” in Figure (h). Instead of the “RecongnizeToString()” method we must use the “RecognizeToFile()” method (line 85) and pass the path of the destination file which we got in the previous step, as a parameter.

Before running the application make sure to add a reference to the “System.Drawing” assembly by going to the Reference Manager in the same way we did in Figure (d). Under “Assemblies” section select “FrameWork” and select “System.Drawing ” as shown in below and click OK.

Figure (k)

Figure (k)

This is the image which I will use for recognition:

Figure (l)

Figure (l)

Now let’s run our application by clicking on “Start” button.

This is the result which I got by clicking the “Read to Screen” button after selecting the above source file through “Select Source” button.

Figure (m)

Figure (m)

And we can also use the “Read to File” button after selecting a destination file using the “Select Destination” button.

Figure (n)

Figure (n)

Here is the destination file after the operation:

Figure (o)

Figure (o)

There are some other properties under “PumaPage” class which can be set for much sensitive and thorough recognition, just play around with them a little bit and you will understand their usage and power in no time.

I hope you understood my explanation and learned something new. If you need any further clarifications, please feel free to contact me. And since this is my very first article I very much appreciate your feedback in order to make my future work much beneficial to you all!

Let’s meet again soon with another article.

Take care :)   Happy Coding!!

874

During the past few articles we discussed the various aspects which involves in C#.NET.  We discussed some of the most important things we have to in programming with C#.NET. Having a good understanding about these programming idioms is very important. Apart from that there is another very important aspect in programming. That is to work with databases.  Applications connected to a database are very common in programming. When it comes to C#.NET there are lots of DataBase Management Systems that could be used. SQL Server, MySql, Oracle… etc.

In this article we would concentrate on one of those DBMSs. It is the most commonly used DBMS with C#.Net. So I thought of sharing some information with you with related to setting up SQL server and using it. This article covers the aspects of installing it. In the following articles we would discuss more on how to program with C#.NET and SQL Server.

SQL Server 2005

First get the SQL server 2005 setup, at present SQL server 2008 is also available. But here we use the 2005 version for the process of installing the product.

  • This is the initial screen of the installation process.

  • Accept the term and agreement and then you would be directed to this page.

  • Then insert the product key, for SQL server 2005.

  • After selecting the necessary components, select ‘default instance’ from the next window.

  • in the next select Local System from “Use the built-In System account”

  • Then in the next window select ‘Mixed Mode’. And enter a ‘System Administrator’ password. This would be the main user of the SQL server and would be used to log into the database system.

  • Then in the next window select ‘Mixed Mode’. And enter a ‘System Administrator’ password. This would be the main user of the SQL server and would be used to log into the database system.

  • After the installation process there would be a link called ‘Microsoft SQL Server 2005’ and ‘SQL Server Management Studio’ would be the main interface of the SQL server.
  • If the server is installed in your local machine, the machine name would be the server name.
  • ‘sa’ would be the login name and enter the ‘sa’ password.

 

In the next article would we would surf around the SQL server and would start connecting a SQL server database with C#.NET.

932

Welcome to another edition of the C#.NET article series in the Digit magazine. During the November edition of the article we concentrated on C# generics. In programming aspects, its applications are limited. So having a good understanding about the ‘Generics’ namespace is quite a handful.

Last time we learned how to declare Lists<> is C#. By using lists we can create an array of objects of any kind. This is a real nice feature in C# which would give the users a good control over what he is doing. In this article we would concentrate on some Generics in C#. Having a good understanding about these data types would expand your knowledge and would give more dimensions in coding efficient codes.

Generics in C#

Difference between C# generics and C++ templates

It’s no accident that the syntax of generics is similar to that of C++ templates, when the syntax for every other element in C# is based on the corresponding C++ syntax. This approach allows you to leverage your existing knowledge. As is typical throughout C#, the designers have streamlined the syntax and removed some of the verbosity. However, the similarities end there, because C# generics behave very differently than C++ templates, and, if you come from the C++ world, you must make sure that you understand the differences. Otherwise, you may find yourself attempting to apply your C++ template knowledge in ways that simply won’t work with generics. The main difference between the two is that expansion of generics is dynamic, whereas expansion of C++ templates is static. In other words, C++ templates are always expanded at compile time. Therefore, the C++ compiler must have access to all template types—generally through header files—and any types used to create the closed types from the template types at compile time. For this reason alone, it is impossible to package C++ templates into libraries. I know that many developers become confused by this fact when learning C++ templates for the first time. I remember plenty of times when it would have been nice to be able to package a C++ template into a static library or a DLL. Unfortunately, that is not possible. That’s why all of the code for C++ template types usually

lives in headers. This makes it difficult to package proprietary library code within C++ templates, since you must essentially give your code away to anyone who needs to consume it. The STL is a perfect example: Notice how almost every bit of your favorite STL implementation exists in header files. Generics, on the other hand, can be packaged in assemblies and consumed later. Instead of being formed at compile time, constructed types are formed at run time, or more specifically, at JITcompile time. In many ways, this makes generics more flexible. However, as with just about anything in the engineering world, advantages come with disadvantages.

Reference: Accelerated C# 2008 by Trey Nash (Chapter 11)

Support for generics is one of the nicest features of C# and .NET. Generics allow you to create open-ended types that are converted into closed types at run time. Each unique closed type is itself a unique type. Only closed types may be instantiated. When you declare a generic type, you specify a list of type parameters in the declaration for which type arguments are given to create closed,

Figure 1: Simple code for generics

In this case, a generic type is declared, MyCollection<T>, which treats the type within the collection as an unspecified type. In this example, the type parameter list consists of only one type, and it is described with syntax in which the generic types are listed, separated by commas, between angle brackets. The identifier T is really just a placeholder for any type. At some point, a consumer of MyCollection<T> will declare what’s called a closed type, by specifying the concrete type that T is supposed to represent. For example, suppose some other assembly wants to create a MyCollection<T> constructed type that contains members of type int.

Efficiency of C# Generics

  • Arguably, the added efficiency when using value types in collections is one of the greatest gains from generics in C#. Whereas a regular array based on System.Array can contain a heterogeneous collection of instances created from many types as long as it holds references to a common base type such as System.Object, it does come with its drawbacks.
  • Added type safety at compile time is always a good thing, because it’s much better to capture bugs based on type mismatches earlier at compile time rather than later at run time.

Generics are very important and useful if you work, for example, with any kind of collections. Because of the backwards compatibility of ASP.NET 2.0, the existing collections couldn’t be modified. Instead, a new namespace named System.Collections.Generic was created. It contains a lot of generic classes, structures, and interfaces like the following:

  • Dictionary
  • List
  • Queue
  • SortedDictionary
  • Stack

In the case of C#, generics are declared and type checked at compile time while instantiated at runtime just like any other object. C#Generics has the following advantages:

  1. The Program becomes statically typed, so errors are discovered at compile-time.
  2. No runtime casts are required and the program runs faster.
  3. Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.

Reference: ASP.NET 2.0 Revealed, by Patrick Lorenz.

Generic Classes and Structs

Overall, declarations of all generic struct and class types follow the same rules as those for regular struct and class types. Any time a class declaration contains a type parameter list, it is, from that point on, a generic type. Likewise, any nested class declaration—whether it’s generic or not that is declared within the scope of a generic type is a generic type itself. That’s because the enclosing type’s fully qualified name requires a type argument in order to completely specify the nested type.

Generic types are overloaded based upon the number of arguments in their type argument

lists. The following example illustrates what I mean:

public class Container {}

public class Container<T> {}

public class Container<T, R> {}

Each of these declarations is valid within the same namespace. You can declare as many

generic types based on the Container identifier as you want, as long as each one has a different count of type parameters. You cannot declare another type named Container<X, Y>, even though the identifiers used in the type parameters list are different. The name overloading rules for generic declarations are based on the count of type parameters rather than the names given to their placeholders.

Generic Interfaces

Along with classes and structs, you can also create generic interface declarations. This concept is a natural progression from struct and class generics. Naturally, a whole host of interfaces declared within the .NET 1.1 base class library make excellent candidates to have generic versions fashioned after them. A perfect example is IEnumerable<T>. Generic containers create much more efficient code than nongeneric containers when they contain value types, since they avoid any unnecessary boxing. It’s only natural that any generic enumerable interface must have a means of enumerating the generic items within. Thus, IEnumerable<T> exists, and any enumerable containers you implement yourself should implement this interface. Alternatively, you could get it for free by deriving your custom containers from Collection<T>.

Generic Methods

C# supports generic methods. Any method declaration that exists within a struct, a class, or an interface may be declared as a generic method. That includes static as well as virtual or abstract methods. Also, you can declare generic methods on non-generic types. To declare a generic method, simply append a type argument list to the end of the method name but before the parameter list for the method. You can declare any of the types in the method parameter list, including the method return type, using one of the generic parameters. As with nested classes, it is bad form to hide outer type identifiers by reusing the same identifier in the nested scope, which in this case, is the scope of the generic method. Let’s consider an example of where a generic method may be useful.

In this article we gave a brief description about the Generics in C#.NET.  These can be used when you are in need to handle collections of data. From the next article we would dive into the world of Threads in C#.NET. Till then have a nice time..

 

981

Welcome to another edition of the C#.NET article series in the Digit magazine. We are back after a break of 2 months. Due to some unavoidable reasons I couldn’t provide an article to the September 2009 edition of the Digit magazine. I am sure that would have given you ample time to do more work on C#.NET and I am sure you would have gathered a good knowledge by now. During the August Edition, we discussed about the use of the Array class which is available in the C#.NET and we discussed it using some code segments as well. It also included some of the methods available under the Array class in C#.NET.

In this article we would like to concentrate on Iteraters and Collections, which are very important programming idioms and are heavily used. Here as usual we would discus some theoretical aspects would underline it using some code segments.

 

What are IEnumerable<T>, IEnumerator<T>, IEnumerable, and IEnumerator?

You’ve seen how you can use the C# foreach statement to conveniently iterate over a collection of objects, including a System.Array, ArrayList, List<T>, and so on. How does this work? The answer is that each collection that expects to work with foreach must implement the Enumerable<T> or IEnumerable interface that foreach uses to obtain an object that knows how to enumerate, or iterate over, the items in the collection. The iterator object obtained from IEnumerable<T> must implement the IEnumerator<T> or IEnumerator interface. Generic collection types typically implement IEnumerable<T>, and the enumerator object implements IEnumerator<T>. IEnumerable<T> derives from IEnumerable, and IEnumerator<T> derives from IEnumerator. This allows you to use generic collections in places where nongeneric collections are used. Strictly speaking, your collection types are not required to implement enumerators, and users can iterate through the collection using a ‘for’ loop if you provide an index operator by implementing IList<T>, for example. However, you won’t make many friends that way, and once I show you how easy it is to create enumerators using iterator blocks, you’ll see that it’s a piece of cake to implement IEnumerable<T> and IEnumerator<T>.

If things are a bit complicated right now, let’s clarify it through some examples.

Figure 1: Iterate through an array through ‘foreach’

In the rest of this section, I’ll quickly go over the salient points of creating enumerators from scratch, and I’ll quickly transition to how to create enumerators the new and improved way using iterator blocks. The IEnumerable<T> interface exists so that clients have a well-defined way to obtain an enumerator on the collection.

Figure 2: the IEnumerable<T> and IEnumerable interfaces

 

This above snippet shows IEnumerable interface, interface is a collection of methods which are not implemented. And are in an abstract state.

In the next example we are going to consider how to use the above mentioned classes. Here let’s build some employee objects using the employee class and try to iterate through them using ‘IEnumerable<T> and IEnumerable interfaces’.

In this code we have written an ‘Employee’ class which would display the basin information of an Employee. It has 2 fields ‘Employee Name’ and ‘Employee Number’

  • Next we would describe a department class which would include the department the employees would belong to. Here we would write implement the ‘IEnumerable<T> interface,

Figure 4: Department class which the employees belong to

 

  • A List is there which would add new class objects. ‘GetEnumerator’ method from the ‘IEnumerable<T> interface is there to iterate through the List to get the stored employee objects.
  • ‘addEmployee’ method would add new employee objects to the list.

 

Figure 5: Adding the employee objects to the List and retrieve them

In the above snippet we are adding each ‘Employee’ to the list and retrieve them and display them. For that we are using a ‘foreach’ statement. Read more about these interfaces and methods to get a broader view.

In the next article we would concentrate more on generics as this a very important aspect in C# coding.

963

Flash Back

During the previous article we started to put our attention towards array in C#.NET which is one of the most important programming idioms available. Arrays will let you store large amount of data (same data type) and provides functionality to use and access them individually. Last week we an introduction was made about arrays explained the available types of arrays. And to explain the content some sample codes were given to explain it deeply.

In this article we would try to learn more about the functionalities in arrays and how the ‘array’class available in C# API could be used in our work. Furthermore we would get to know about some of the more complex data collectors such as vectors, iterations and collection types as well. We are hoping to explain them through some code examples as well. Unlike arrays which could contain only one data types, some of these data structures can contain different data types that would be huge asset when programming.

 

Array class in C#.NET

What is System.Array Class?

The type System.Array is the abstract base type of all array types. An implicit reference conversion exists from any array type to System.Array and to any interface type implemented by System.Array. An explicit reference conversion exists from System.Array and any interface type implemented by System.Array to any array type. System.Array is not itself an array-type. Rather, it is a class-type from which all array-types are derived.

The Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class but it provides CreateInstance method to construct an array. The Array class provides methods for creating, manipulating, searching, and sorting arrays.At run-time, a value of type System.Array can be null or a reference to an instance of any array type.

In the last article we discussed System.Array Class Properties. In the table mentioned below the methods which belongs to the class. The Array class provides methods for creating, manipulating, searching, and sorting arrays. Array class provides three boolean properties IsFixedSize, IsReadOnly, and IsSynchronized to see if an array has fixed size, read only or synchronized or not respectively. The Length property of Array class returns the number of items in an array and the Rank property returns number of dimensions in a multi-dimension array.

 

Method Description
BinarySearch

 

This method searches a one-dimensional sorted Array for a value, using a binary search algorithm.
Clear

 

This method removes all items of an array and sets a range of items in the array to 0.
Clone This method creates a shallow copy of the Array.
Copy This method copies a section of one Array to another Array and performs type casting and boxing as required.
CopyTo This method copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.
CreateInstance This method initializes a new instance of the Array class.
GetEnumerator This method returns an IEnumerator for the Array.
GetLength This method returns the number of items in an Array.
GetLowerBound This method returns the lower bound of an Array./p>
GetUpperBound This method returns the upper bound of an Array.
GetValue This method returns the value of the specified item in an Array.
IndexOf This method returns the index of the first occurrence of a value in a one-dimensional Array or in a portion of the Array.
Initialize This method initializes every item of the value-type Array by calling the default constructor of the value type.
LastIndexOf This method returns the index of the last occurrence of a value in a one-dimensional Array or in a portion of the Array.
Reverse This method reverses the order of the items in a one-dimensional Array or in a portion of the Array.
SetValue This method sets the specified items in the current Array to the specified value.
Sort This method sorts the items in one-dimensional Array objects.

Table2:Methods in System.Array class

Previously we concentrated on a code sample which was based on standard data types, but now let’s put our attention on an example which uses objects to form an array. This could very important when you are applications like games where you would need to work with number of objects.

The assignment from dogs to animals and from cats to animals is something that you definitely

can’t do in native C/C++. Arrays are assignable as long as their rank matches and the contained type is convertible from one to the other. Here both ‘Dogs’and ‘Cats’classes are derived from ‘Animals’class.

P.S:Since these are empty classes, the output won’t provide anything. These could be implemented and used in various application where handling of multiple of object sin necessary.

Figure 1:Array with Objects

 

Figure 2:Various functionalities of System.Array

·       Here an array with a fixed number of elements is created. Then with the help of an ‘if’statement that condition is checked using the ‘IsFixedSize’method. Since array has 2 elements which is a fixed value, the desired output will be displayed.

·       This is a very important method to check the stability of an array.

 

 

Figure 3:Use of Binary Search in Array class

·       In this code Binary search is used to search for the entered word. It would be search in the array. For that the ‘BinarySearch’method is used.

·       The word which needs to be searched would be entered as an object. Then it would be entered to the ‘BinarySearch’as a parameter. If the value excits in the array, zero or a positive value would be generated. If not it would be a negative value.

·       Like wise the methods which comes under ‘System.Array’can be used for various operations that needs to be done using arrays.

In the next article we would look into more data structure like Vectors, vectors are much more flexible than arrays, we would see the reason why and how it can be used in programming. Meanwhile hope that you would do more research inthese and get to know more things about arrays.

 

1066

Welcome to the C#.NET
section of the Digit magazine. During the last session we had a closer look at
some of the most important object oriented concepts going around. Inheritance,
Encapsulation and Polymorphism are some of them. There we created some C# code
which would implement the above concepts and illustrated them one by one.
Furthermore we emphasized the value of those concepts when we are doing
programming. Hence having a good idea about the use of object oriented concepts
would be really advantageous.

Thus far we discussed
some important C# theories as well as some valuable object oriented concepts. From
now on will dive into some tough programming concepts in C#, these are very
important and would help to improve your knowledge in the subject by quite a
lot. In the next few articles we would discuss on Arrays, Collection types and
Iterators in C#. NET as well as Exception handling as well. We would spend some
time on these as they are very important programming techniques. In this week we
will start to work on Arrays, and gradually we would move into more advance
data collections.

Arrays in C#

What are arrays..?

An array is a data
structure that contains several variables of the same type. Arrays are declared
with a type. That type could be an Integer, String, and Float… or can even be
another object.

An array has the following
properties:

  •   
    An array can be Single-Dimensional, Multidimensional
    or Jagged.

 

  •  
    The default value of numeric array elements are
    set to zero, and reference elements are set to null.

  •    A jagged array is an array of arrays, and
    therefore its elements are reference types and are initialized to
    null.

 

  •   
    Arrays are zero indexed: an array with n elements is indexed from 0 to n-1

 

  •   Array elements can be of any type, including an
    array type.

 

  •   Array types are reference types derived from the
    abstract base type Array. Since this type implements
    IEnumerable
    and
    IEnumerable, you can use foreach iteration on all
    arrays in C#.

 

 

An Array can be defined as,

int [] intArray;

The following code declares an array, which can store 5 items starting from
index 0 to 4.

int [] intArray;

intArray = new int[5];


The following code declares an array that can store 100 items starting from
index 0 to 99.

int [] intArray;

intArray = new int[100];

P.N: In a
array we should explicitly give the length or the size of the array, if not we
have to declare the elements of the array with in “{}” (curly brackets). If you
don’t follow these practices the complier will issue an error.

string[] strArray = {“Ronnie”, “Jack”,
“Lori”, “Max”, “Tricky”};

Single Dimensional Arrays

Single-dimensional
arrays are the simplest form of arrays. These types of arrays are used to store
number of items of a predefined type. All items in a single dimension array are
stored in a row starting from 0 to the size of array -1.

In C# arrays are objects. That means declaring an array doesn’t create an
array. After declaring an array, you need to instantiate an array by using the
“new” operator.

int [] intArray;

intArray = new int[5];

Multidimensional Arrays

A multidimensional array is an array
with more than one dimension. A multi dimension array is declared as following:


string[,] strArray;

After declaring an array, you can specify the size of array dimensions if you
want a fixed size array or dynamic arrays. For example, the following code two
examples create two multi dimension arrays with a matrix of 3×2 and 2×2. The
first array can store 6 items and second array can store 4 items respectively.

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };

string[,] names = new string[2, 2] { {“Rosy”,”Amy”},
{“Peter”,”Albert”} };

Jagged Arrays

Jagged arrays are often called array of arrays. An element of a jagged array
itself is an array. For example, you can define an array of names of students
of a class where a name itself can be an array of three strings - first
name, middle name and last name. Another example of jagged arrays is an array
of integers containing another array of integers. For example,

int[][] numArray = new
int[][] { newint[] {1,3,5}, newint[] {2,4,6,8,10} };

Again, you can specify the size when you call the new operator.

Mixed
Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays.
Multi-dimension arrays are also called as rectangular arrays.

P.N:  In most cases use of single dimensional arrays
is more frequent, it is seldom that you find other type of arrays which we
mentioned above would be used in conventional programming, unless it is a game
or some kind. But it is good know that such kind arrays types also exists.

  • In
    an array it is necessary that you should access every single array element
    in order to retrieve data from them.
  • To
    do that we need to use a ‘for’ loop to go through the entire array. The
    number of times the ‘for’ loop would loop would depend on the length of
    the array. This is also possible in C#.
  • But
    the specialty in C# in that it allows a keyword called ‘foreach’ to go
    through the array and access each and every element.

This sample code illustrates it,

int[] numArray = {1, 2, 5, 6, 10, 14, 115};
foreach (int num in numArray)
{
System.Console.WriteLine(num.ToString());
}

To get a broader idea about what we
discussed so far, let’s look at an example


                                                                  

 

Figure
1: Output of the code sample

 

static void Main(string[]
args)

        {

            int[]
numbers = new int[3];

            // adding
elements to the array

            numbers[0] = 1;

            numbers[1] = 3;

            numbers[2] = 5;

            Console.WriteLine(“—————”);        

            foreach
(int i in
numbers)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine(“===============”);

            Console.WriteLine();

            // Array
declaration with elements

            string[]
names = {“Saman”,“Nadun”, “Kasun”,
“Isuru” };

            foreach
(string name in
names)

            {

                Console.WriteLine(name.ToString());

            }

            Console.WriteLine(“===============”);

            Console.WriteLine();

            // Two
dimensional array

            string[,]
strArray = new string[,]

            {

            {“Rosy”,“Amy”},

            {“Peter”,“Albert”}

            };

            foreach
(string str in
strArray)

            {

                Console.WriteLine(str);

            }

            Console.ReadLine();

        }

Figure
2: Code sample for the implementation of arrays


  • Thus far we declared arrays using normal
    coding, but in C# there is a inbuilt class specifically designed to be used in
    matters related to handling on arrays.

 


  • The Array class, defined in the
    System namespace, is the base class for arrays in C#. Array class is an
    abstract base class but it provides “CreateInstance” method to construct an
    array. The Array class provides methods for creating, manipulating, searching,
    and sorting arrays.

The
below table contains some properties of the array class:

Figure
3: The System.Array Class Properties

In the next article we
would discuss more about this array class and would inspect some code
associated it to it. Furthermore we would get to know about some of the more
complex data collectors as well.

1133

Welcome to the C#.NET section of the Digit magazine. During the last session we had a closer look at the access modifiers in C#. We saw how they are used and so had a glance at their access capabilities first hand. As we mentioned earlier access modifiers are a very important section in every programming language. They would be used in many different ways in doing programming; hence in long run having an open idea and clear mind on access modifiers could be very advantageous.

In this week we’ll have a look at some object oriented concepts. After all C# is an object oriented programming language, hence all object oriented concepts we know of is applicable and implemented on C#. Here we would talk about encapsulation, polymorphism and inheritance. We would try to implement them through C# as well.

Let’s take a look at each of those concepts in detail.

 

Encapsulation

Encapsulation is an object-oriented principle of hiding the internal state and behavior of an object, making your code more maintainable. In C#, you can manage encapsulation with access modifiers. For example, the public access modifier allows access to any code but the private access modifier restricts access to only members of a type.  Other access modifiers restrict access in the range somewhere between public and private. While you can use any of the access modifiers on type members, the only two access modifiers you can use on types are the public and internal.

using System;

 

namespace Encap

{

    class BankAccount

    {

    public double getBalance()

    {

    return 10000.00;

    }

    }

}

Figure 1: Code on Bank Account Balance

 

In this method ‘getBalance()’ is in a public context. A value is returned from the class. The method is public meaning that it can be called by code that is external to this class.  Now, you can write the following code, elsewhere in your program, to use this method:

BankAccount bank = new BankAccount()

double balance = bank.getBalance();

 

Figure 2: Getting the value in the class

 

In here an object of the ‘BankAccount’ is created. The method would be accessed from that object. Though this is an easy way of getting data, security wise it isn’t very good. Remember that the default access for a type member is private, which we’ll talk about next.  This means that if you forget the public modifier, and didn’t use any modifier at all, you would receive a compiler error.  

The following example would show how to use ‘private’ modifier and use the theory of encapsulation in the code.

 

using System;

 

namespace Encap

{

    class BankAccountPrivate

    {

    private string name;

 

    public string customer_Name

    {

    get { return name;}

    set { name = value;}

    }

    }

}

Figure 3: How to use private modifiers in the code

 

It’s common to encapsulate the state of your type with properties.  In here you can see how the name of the customer is held in the ‘name’ field, but it is wrapped (encapsulated) with the ‘CustomerName’ property. Because ‘name’ is declared as private, code outside the ‘BankAccountPrivate’ class can’t access it directly.  They must use the public customer_Name’ property instead.

 

Now you can change the implementation of ‘name’ in any way you want. This is secure rather than having ‘public’ access to the members. These are two extremes in accessing members. Encapsulation is a concept which is very mush related with access modifiers and behaviors.

 

Inheritance on C#

Classes and Structs are ‘blue-prints’ or templates from which we instantiate (create) objects Example a car may be created based on its blue print Car is the object and blue print is the class (or template).

These are the available types,

An object can be of the following types – Class or Struct There are many differences between the two ‘types’ The main difference between the two is the way in which they are stored in memory and the way they are accessed Classes are also called reference types Structs are known as value types Classes are stored in a memory space called ‘heap’ and Structs are stored in a memory space known as ‘stack’.

Inheritance:

C# supports two types of Inheritance mechanisms

·     Implementation Inheritance

When a class (type) is derived from another class (type) such that it inherits all the members of the base type it is Implementation Inheritance

·     Interface Inheritance

When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

 

Classes support both Implementation and Interface inheritance as they could be inherited from both classes and interfaces. But strcuts only get inherited from interfaces. Structs cannot be derived from another class they are always derived from SystemValueType

P.N: Unlike C++, C# does not support multiple implementation inheritance ‘A’ class cannot be derived from more than one class However; a class can be derived from multiple interfaces.

 

using System;

 

namespace Encap

{

    abstract class Car

    {

    public void startCar()

    {

    }

 

    public abstract bool goForward();

 

    public void stop()

    {

    }

 

    public abstract void turnCar(int whichWay);    

    }

}

Figure 4: Class Car for implement Inheritance

 

In this example class called ‘Car’ is shown, it comprises of few methods. Here you would see some methods have the keyword ‘abstract’. And furthermore the class too is abstract. As name implies abstract methods and classes are not implemented. They should implement overridden in a subclass of the abstract class. Abstract classes and methods are very important. There are some certain facts that should be kept in mind when dealing with abstract classes and methods.

·Abstract class does not necessary have abstract methods.

·In an abstract class few or almost all the methods can be abstract.

·If a method is non abstract, then the class that it belongs must be abstract class.

 

P.N:  A ‘C#’ abstract class contains abstract members which define what a subclass should contain. These abstract members only declare that a member of a particular type is required; it does not implement the member. Implementation of abstract members takes place within the derived class. A subclass which derives from an abstract class and fails to implement abstract methods will fail to compile.

In the above example there are abstract as well as non abstract classes.

Let’s see how this class is sub classed, this is where the concept of inheritance comes into play.

using System;

 

namespace Encap

{

    class SportsCar : Car

    {

    public void startEngine()

    {

    }

 

    public override bool goForward()

    {

    return false;

    }

 

    public override void turnCar(int whichWay)

    {

    }

 

    public void stop()

    {

    }

    }

}

Figure 5: Inheritance in C#.NET

 

Here you could see some of the methods are implemented and some new methods are there as well. “SportsCar : Car” is the way to inherit classes in C#.NET. This would mean that class “SportsCar” is inherited from “Car”. Inheritance is a pretty important and a very useful OOP concept. When inherited a class gets all the qualities from its parent class. Apart from that new qualities and attributes could be included in the new class.

When inheriting a class, you should override methods in its parent class this is very important. In C# we use the keyword ‘override’ to implement inherited methods from a superclass. It is quite evident in the example given, Try to read more on inheritance in C# and gather more knowledge.

 

Polymorphism

 

This is another very important object oriented concept. Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

Here is an example which emphasizes those qualities. This is the parent class that we would use to show the example.

 

using System;

 

namespace Encap

{

    class DrawingObejcts

    {

    public virtual void drawObect()

    {

    Console.WriteLine(“Draw Common Obecjts…..”);

    }

    }

}

Figure 6: Parent class for Drawing Objects

 

The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overridden in the derived classes.

To create a virtual member in C#, use the virtual keyword:

public virtual void drawObect().

Under mentioned are the classes which were derived from the parent class mentioed above, here as in the previous example, a method is over ridden and the content is changed based on the class that it operates on.

P.N : These classes inherit the DrawingObject class. Each class has a drawObect() method and each drawObect() method has an override modifier. The override modifier allows a method to override the virtual method of its base class at run-time. The override will happen only if the class is referenced through a base class reference. Overriding methods must have the same signature, name and parameters, as the virtual base class method it is overriding.

using System;

 

namespace Encap

{

    class DrawCircle : DrawingObejcts

    {

    public override void drawObect()

    {

    Console.WriteLine(“Drawing a Circle…..”);

    }

    }

}

namespace Encap

{

    class DrawingObejcts

    {

    public virtual void drawObect()

    {

    Console.WriteLine(“Draw Common Obecjts…..”);

    }

    }

}

namespace Encap

{

    class DrawSqaure : DrawingObejcts

    {

    public override void drawObect()

    {

    Console.WriteLine(“Drawing a Square….”);

    }

    }

}

Figure7: Example on Polymorphism, the classes that were used.

 

 

1005

During our April version we concentrated on the variables related to C#.NET. We discussed how variables are declared and initiated. You saw how easy it was to get into terms with the coding patterns and variable handling in C#.NET. Also discussed some examples where we used some variables in some sample codes. I assume that you must have done some thorough research on variables types in C# and how those are used in specific occasions. I believe that by now you should be enjoying programming with C#. NET and would be itching to go ahead.

 In this May version of C#.NET lesson, we would move one step forward. We would discuss about access modifiers, encapsulation and few other concepts. These are some of the most widely used concepts in programming especially in Object Oriented Programming. Hence this would be valid not only to C#.NET but also for other Object Oriented programming languages as well.

Access Modifiers

Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn’t have access to certain features. Knowing about proper access modifiers and using them in a proper way would give you greater control over a programming language. There are instances where we can handle scenarios in a much safer and effective manner by using proper access modifiers.

In C#.NET there are few types of access modifiers, whose use would change based on the use of each modifier. Furthermore, visibility would change based on each modifier. Under mentioned are the access levels in C#.NET.

  • There are five levels of access allowed in .NET. The first access level provides access to everyone with no restrictions. This is called public, so any classes, methods, or properties defined as public are visible to all other code.

Ex: suppose there are 2 classes called Cat and Dog. A public method ‘run’ in Cat can be called in Dog. Hence all the features of ‘run’ would be there in Dog as well.

  • The exact opposite of this public access is private, which limits access to its own. Properties or methods defined as private are only accessible by code contained within the same class. Private elements may not be accessed by derived classes or other classes.

Ex: If a variable is declared inside a method, then that variable would only be valid inside that variable, it won’t be visible outside that method.

  • There are a few other access levels between the public and private spectrum. The protected access level says that properties and methods defined as protected are visible within its own class and any classes derived from it.

Ex: If there are 2 classes, where one class is a super class of the other, ‘protected’ keyword could be used for visibility. One class could be made the sup class of other. When that happens the variable could be made visible.

  • It says properties and methods defined as a friend or internal are accessible to all code by any class within its containing assembly. This level may be combined with the protected access level to define properties and methods that are accessible by all derived classes, as well as any classes within its assembly.

Here is a brief description about the access modifiers in C#.NET.

  • public: No access restrictions.
  • protected: Access limited to containing/derived classes.
  • internal: Access limited to containing type.
  • protected internal: Access limited to the current project.
  • private: Access limited to containing/derived classes and the current project.

Default Access

A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types:

  • enum: The default and only access modifier supported is public.
  • class: The default access for a class is private. It may be explicitly defined using any of the access modifiers.
  • interface:The default and only access modifier supported is public.
  • struct:The default access is private with public and internal supported as well.

The default access may suffice for a given situation, but you should specify the access modifier you want to use to ensure proper application behavior.

In this example let’s see how access modifiers are used to hide the visibility of variables. The purpose and use of each line is explained with each code segment.

  • All ‘enums’ are based upon an underlying integral type, which if not specified, defaults to int. The underlying type of the enum must be an integral type that is one of the following: byte, sbyte, short, ushort, int, uint, long, or ulong.
  • ‘class’ is a blue print of an object, all the code segments which associates with an object is included in a class. And based on that object s could be made. If there a class called ‘Person’

Ex: Person p1 = new Person (), Person p2 = new Person ();

p1 and p2 are object names.

An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.

A struct allows you to create new value-type objects that are similar to the built-in types (int, float, bool, etc.). Structs are custom value types that store the values in each field together. They do not store referenced data, such as the character array in a string.

Figure 1: Access Modifiers Visibility

In this example all the four variables we declared are applicable to the entire class ‘First’. Class ‘NestedClass’ is an inner class of the class ‘First’. Hence those variables are accessible from the class from that inner class.

P.N: In C#.NET when you press the ‘.’ a list appears. If a particular variable, method isn’t visible from certain location in the class, that variable or method wouldn’t be in that list. During the development stage this would give the developer an indication about the visibility of that particular variable or method.

Figure 2: More examples on Access Modifiers

Segment A shows, making an object of the ‘First’ class, and trying to display the variables which are in that class. As you can see ‘var_one’ and ‘var_two’ would display errors as they are not visible through the object. Because making them ‘private’ would mean that these are only visible within the class, not from outside. There isn’t such problem with the other two variables.

In the next section class ‘DerivedClass’ had inherited from the First class. In this case the scenario changes a bit. But as usual ‘var_one’ with private access modifier returns an error message, because it is not accessible from another class. But variables with ‘protected’ access modifier can be accessed through this derived class. This is a very important fact when it comes to programming.

In the ’C’ section it is very similar to the ‘B’ section, the only difference is that this is a private class and ‘Derived’ class is given as the argument to the method. But because of the ‘Derived’ class, the result is identical to the ‘B’ section.

The last section is similar to the ‘C’ section, but the different is that the argument here is the ‘First’ class, hence the output is similar to section’ A’. This is similar to creating an instance of ‘First’ class. Hence the results too are similar ‘A’.

As you saw in the previous examples the access of the variables and methods could differ based on the modifier we use during each occasion. Try to understand more about these access modifiers and try to get used to the usage of each of the modifiers.

This would be the end of our article for the month of May. In our next article we would concentrate more on object oriented concepts, which would be very advantageous in programming with C#.NET.

1885

Flash Back

During the last article of this series we had a look on our first C#.Net code. And I hope it would have given you some confidence to start coding with C#.NET. You saw how easy it was to get into terms with the coding patterns in C#.NET.  The .NET framework had made the task of the developer very much easier. Hence you’ll start to enjoy programming with C#.NET. In this article we’ll dive deeper into the world of C#.

In this article we would try to get into terms with variables in C# and we’ll see what the available variable types are in C#. In our last lesson we used some variables in our sample programs. Since it wasn’t the best time I didn’t try put too much attention into it. Now I think by now you have tried out some experiments by yourself with C#, and you are ready to move into some very important aspects not only in C#.NET, but also in most other programming languages as well.

 

Variables

Before talking about C# variables let’s consider about variables in a more generic perspective. Seriously,

  1. What are variables..?
  2. Why are they so important?

Here are the answers for those questions. Variables are temporary memory locations in the computer. They help to store values in the computer. In programming it is very useful to store values in this manner. So as a programmer you need to have a good understanding about the variable types in a particular programming language.

In other words, Variables represent storage locations. Every variable has a type that determines what values can be stored in the variable. C# is a type-safe language, and the C# compiler guarantees that values stored in variables are always of the appropriate type. Variables can hold either value types or reference types, or they can be pointers. Variable could be of two types Value types and Reference types.

 

Value types

A variable ‘x’ contains a value type; it directly contains an object with some value. No other variable ‘x’ can directly contain the object contained by ‘x’.

Reference types

A variable ‘x’ contains a reference type, what it directly contains is something which refers to an object. Another variable ‘x’ can contain a reference to the same object referred to by ‘x’.

 

There are number of variable types in C#.NET. Each type is used in different occasions to represent different values and the amount one can store would differ from one type to another.

 

Figure 1: Some Variable Types in C#

 

As you can one type of data can be categorized into several sub types and after that they are considered as separate data types. The categorization is based on the amount of data that one variable could contain.

Ex: Type ‘Integer’ has sub categories based on its storage capacity. (ushort, uint, ulong, etc..)

A variable can be compared to a storage room, and is essential for the programmer. In C#, a variable is declared like this:

<data type> <name>;

an example could look like this:

string name;

that’s the most basic version. Usually, you wish to assign a visibility to the variable, and perhaps assign a value to it at the same time. It can be done like this:

<visibility> <data type> <name> = <value>;

An example could look like this:

private string name = “Saman”

We’ll discuss about access modifiers and encapsulation in the next lesson.

Let’s have a look at a simple example which uses variables.

 

Figure 2: Using Variables in C#.NET

 

P.N:  The System imports of this example are removed from this example.

In our last article we experimented on Graphical User Interface elements like Forms and Text Fields, so this time we’ll have look at C# consoles.

Let’s have a closer look at that example,

As you can see too variables called ‘name’ and ‘address’ are declared at the top. If you want you can assign ‘null’ to each of them. When you are doing large programs that is a very god practice to have. Furthermore I have commented what I am doing in the code that too is a very good practice to have when coding. It will not only help some other person who is reading the code, but later on you too might get benefited from it.

“Console.ReadLine();” will assign the user entered value to the variables we declared.

“Console.WriteLine(“You are ” + name + “, ” + “from ” + address);”

Would display that result on the on the Console screen,

 

Figure 3: Output through the console window.

 

“(“You are ” + name + “, ” + “from ” + address);”

Here you’ll notice that string we entered and string values in variables are combined through a ‘+’ sign. This is called string concatenation. This is a very useful technique to know, one that will be very useful in programming. We’ll be going lot of concetanation related things in this series.

Earlier we talked about two variable types in value type and referance type, let’s have a look what reference type is.

The pre-defined reference types are object and string, where Object is the ultimate base class of all other types. New reference types can be defined using ‘class’, ‘interface’, and ‘delegate’ declarations.

Reference types actually hold the value of a memory address occupied by the object they reference. Consider the following piece of code, in which two variables are given a reference to the same object (for the sake of the example, this object is taken to contain the numeric property ‘myValue’).

Object name = new Object ();

x.myValue = 10;

object y = x;

y.myValue = 20;

After this both x and y would be equal to ‘20’.

Let’s consider about a string for reference types now,

string name = “saman”

string name1 = name;

name = “nadun”

 

What happens is that a new string object is created for ‘name1’ to point to. Hence, following this piece of code, name equals “nadun”, whereas s2 still equals “saman”.

The reason for this behavior is that string objects are ‘immutable’. That is, the properties of these objects can’t themselves change. So in order to change what a string variable references, a new string object must be created.

Before wrapping up this article for this edition, will have another example, this time using type casting as well,

Type casting is a technique where one variable type is converted to another; this can’t be done every time. And at times could result in loss of data as well.

Ex: when converting a ‘float’ to an ‘int’, floats floating point value may get lost and we might lose some data I the process.

 

Hence have to be very precise when doing type casting. But this too is a very important practice when it comes to programming.

 

Figure 4: Sample Code on type casting

In here you will see the usual variable declaration, after that you need to convert textbox values to whatever type you need to assign it to. By default all the textbox values are as strings. So here I had converted text box values into type ‘int’ and ‘float’. There are C# in- built methods for this work;

Ex: age = int.Parse(textBox2.Text);

salary = float.Parse(textBox3.Text);

In the next line I have done an explicit type cast. It is very simple to do it. You have to give the type you want it to become in a parenthesis and assign it to similar type of a variable you want.  Here ‘salary’ is in float and it is assigned to an ‘int’.

Ex: int salary_to = (int)salary;

After tht these results are displayed in a Message box. The result is as follows.

 

 

Figure 5: Form for the example and the Final Output

 

This shows some drawback of type casting, after the type cast Value ‘salary’ has lost his floating point values. So have to be very precise in doing this operation.

That’s it for this edition on C#.NET. In our next edition we’ll have look at access modifiers, encapsulation and few other concepts. Till then enjoy and have a nice time..!

For more on Data types you can visit:

http://msdn.microsoft.com/en-us/library/aa691160(VS.71).aspx