We all understand the concept of boxing and unboxing in C# but type casting is a bit more complicated and we do have more than one option to accomplish it.

The two options that we have is 1) Have an explicit cast  to specific type or 2) Use the as keyword for type casting. Let’s look at each one of those in a little detail in code

 

I am going to call the type casting without any keyword as standard type casting.  Below is a code example of one of the ways of doing it right.

object obj1 = new object();

try
{
    Person person1 = (Person)obj1;
    Console.WriteLine(person1);
}
catch(InvalidCastException castException)
{
    Console.WriteLine(castException.Message);
}

It is apparent from the code that the object we are trying to cast to typeof Person is not actually a person and hence will be unsuccessful, so we are prepared for it by catching the InvalidCastException. This is exactly the problem when using the standard type casting.

We can avoid getting an exception during type casting by using the as keyword. Below is the code example of one way of doing that

object obj1 = new object();
Person person2 = obj1 as Person;
 if (person2 != null)
 {
     Console.WriteLine(person2);
 }
 else
 {
     Console.WriteLine("The person was not the original type of the object");
 }

As we can see from the code above, we used the as keyword to type cast and since the obj1 was is not of the type Person we will get back null as the result of the cast.

 

I know. The next question one would ask as to why is better than catching an exception since it is almost the same amount of code?

 

The answer to that question is performance. It is always expensive to throw an exception because of the additional work that needs to done by the runtime like colleting the stacktrace, increase in memory pressure sue to the page faults, etc

 

There is one catch while using the as keyword though, the as keyword only works for reference types or nullable types, which is understandable since it either returns the casted object or null and there no option to return null in case of failure for non nullable type (value type), it can’t be used there.

 

In summary, we should try to use as wherever possible as checking for null is definitely preferred as compared to throwing an exception, however if we must use type casting we should catch the specific InvalidCastException for better performance.

 

Although there is not much to the source code, regardless it could be found at github

 

Any questions, suggestion or feedback is always welcome.

Hey guys,

Today I am going to share a program that I wrote sometime back when I was learning to work with Selenium. I had a lot of people commenting and subscribing on my blog and I wanted to figure out if those emails were valid or not so I found out a bunch of websites that could do that for you but I did not want to go through the exercise of copy pasting and verifying one email at a time. So I wrote a selenium program to do that for me.

 

The website did have a bulk purchase program but the minimum that one could purchase was 3000 emails and I needed to verify like a 100 hence automation to the rescue.

To write a program similar to this you would need to know C# and little bit of html/css and working knowledge of selenium

 

I just tried this program recently and found out that it needed a fix. So I have fixed the program and its available on my GitHub page. This would give you a basic infrastructure and knowledge to write a selenium automation. This program is only educational purposes. I request you to not to use it for any other reason.

 

Here are a few screenshots from the program

Start Screen

Start Screen

 

Select Emails To Verify

Select Emails To Verify

 

See App In Action

See App In Action

 

Feel Free to provide your feedback, comments and suggestions

Hey Guys,

I have developed a simple CSharp application that gives you random characters to type and records the key presses and also increases the speed of the letters that come for typing.

Have a look at the sceenshot of the app and also the video below.

 

 

 

Have a look at the demo video

The source code of the application can be found here.

 

What do we do and what does IDE do

The C# program can do whatever you want it to but it will take much more than just dragging and dropping the controls in visual studio. Visual studio does provide you with the code but that is just the start point for our application and we need to write C# code for our application to perform the task we want it to do. Let’s see what Visual Studio can do for us.

  • When we create a new Windows Forms Project in visual Studio, it adds an empty form to the project. What IDE does here is creates the files and folder for the project which are created from a predefined template that contains the basic code to create and display a form.
  • When we drag and drop a button onto the form we see some of the C# code for the button property is automatically added by visual studio. What IDE does here is add the code to Form1.Designer.cs which adds the button to the form. When we double click the button then the code to handle the click of the button is added to this file.
  • Visual Studio presents us with the property window in the IDE that we can use to set the various properties of the button. What IDE does here is update these values into the Form1.Designer.cs.

Where programs come from

Actually a C# program just starts out as a few lines of code in a couple of files and finally it runs on a computer. The following steps if how we do it.

  • Program start out as source code – IDE is nothing more just a program that helps us creating, editing and managing our code files and resources. It bundles all these files into a solution by creating a .sln file and a folder that contain other files. The solution file has a list of project files (i.e. .csproj) in the project. The project file contains the files associated with the program.
  • .NET Framework Tools for programming – All the controls that we use in our code are provided as provided as part of the .NET framework. Also there is lot of underlying code for default functionalities like the maximize and the minimize buttons in a button. So C# is just a language using which we access all these controls and their existing functionalities and write new functionalities. The .NET framework is divided into the namespaces which we have already seen. We include the part of .NET framework we need in our application by specifying the using keyword at the top of our code file. Ex – using System.Windows
  • Build the program to create an assembly – When we build our application by using the Build Solution or Build Project option then the IDE runs the C# compiler which compiles our project into a exe or a dll depending on the project type we have selected (class library compiles into a dll and applications compile into exe). We can use this exe to run the program and when press F5 to debug our application then IDE runs this exe and provides additional options to debug the program i.e. pause or add breakpoint to a program.
  • CLR runs the program inside itself – When we run the exe then CLR (Common Language Runtime) kicks in and acts as the layer between our program and Windows. Before C# in your program itself we had to deal with the complexity of communicating with the hardware and low level stuff but with .NET this taken care by CLR. CLR does the translation of our code to machine code so that computer understands it.

How Does the IDE helps us

  • Solution Explorer – It shows us everything that is present in our project. This shows us all the files, folder, references and resources in our project.
Visual Studio Solution Explorer

Visual Studio Solution Explorer

  • Tabbed View – The IDE provides a tabbed view for accessing and editing the various files simultaneously. We can use Ctrl + Tab to switch between the opened tabs in Visual Studio.
Visual Studio Tabbed View

Visual Studio Tabbed View

  • IDE helps write code – The Visual Studio IDE has a feature known as IntelliSence that helps developers writing the code. While we are typing code in the VS IDE we can see small Windows popping up. It shows us the various options we can select.
Visual Studio Intellisence

Visual Studio Intellisence

It also provides the various inbuilt code snippets to auto type the code for us. For example if we want to add the code for a MessageBox we can type mbox and press tab twice and we will be able to see something like below.

Visual Studio Code Snippets

Visual Studio Code Snippets

 

  • IDE helps in tracing errors – When we build our code using the IDE we see the list of compiler errors along with the details and the location of the error.  Also when we debug our program the IDE firsts saves the changes in the project and then shows the compile time error if any.

Changing in IDE means changing the Code

Whenever we are changing anything in the properties window or the design the application all these changes are also reflected in the code. It might seem easier to drag drop controls onto our form but the IDE generates the code in the background.

Dissecting a Program

All the C# programs consist of namespaces, classes and methods which makes our life easier. Whenever we are writing a new class or a form the namespace need to be specified so that the code is separated from the .NET framework libraries. A Class is some code which consists of methods and properties to get the work done.

  • The first part of our program is the one that specifies the .NET classes we need in our program. This is done by using statements as shown below. We can also refer other classes as well which are present in other namespaces. If we do not want to use the using statements we can use the FullyQualified namespace for any class to use it.
Visual Studio Using Statements

Visual Studio Using Statements

  • The C# program is divided into classes. Generally most classes to one thing to keep them logically separated on the basis of what they do. So everything inside the first and last curly braces is part of Chapter02 namespace and the content between the second and second last curly braces is part of the class Form1. So to look for the content of a particular class or namespace we look for the matching curly braces. This class was created by the IDE when we asked it to create a Windows Form application for us.
Visual Studio Classes

Visual Studio Classes

  • Classes contain methods that perform the actions as specified. A method takes some input and performs some action and might produce some output called as the return value. The class we saw makes call to a method called InitializeComponent().
  • A statement is a single line of code. Like in the image above we can see we have added a statement as MessageBox.Show(“Test”); When programs calls a method then statements in that method are executed in sequence. Then method returns to where the method was called from when it either encounters a return or no more statements are available to execute.
  • All programs in C# start at one and only Main method. When we created the Windows Forms application the IDE automatically added the Program.cs file which contains the Main method. This is the entry point of this application and is the first method that will run.
C# Main Class

C# Main Class

It’s not necessary that we keep this Main method as the entry point for our application. We write another Main method in a differ class and make it as the entry point for our application.

  • We can have multiple classes in the same namespace. When a class is public all the other classes in the program can access it. A namespace can span multiple files. So can a class but we need to use the partial keyword for a class to split across multiple files.
  • A variable is something in which our program stores all the data whether it is a document, image or a message. We can declare the variable as shown below. When we declare a variable we mention its type and name. When the program is compiled the compiler check if have assigned value of correct type to the variable. The values of the variable might vary at different times in the program.
C# Variables

C# Variables

The assignment of values to the variable is done in the following way.

C# Variables

C# Variables

  • The C# program is familiar with the maths operators like +, -, *, /, etc. Let’s see what different combination of these means
    • = means assignment of a value to a variable
    • += means adding the value to the variable and then assigning it to the same variable. -=, *= and /= have similar meanings as you might guess.
    • ++ means incrementing the variable by 1 and – means decrementing the variable by 1.
    • != means not equal to.
    • == means comparison
    • We can use the debugger to see the values of the various variables at runtime by placing a watch on the variable on whose value we are interested in. So if you want see the value of variable sin a line of code while debugging the code we can do that by placing a breakpoint at that location by pressing F9 and remove it by pressing F9 again.
    • Loop will perform an action over and over. Different loop in C# are
      • For – As we can see in the example below the action inside the for loop will be performed till the evaluation of i<10. We need to be really careful while using loops because if the condition becomes false the loop might run indefinitely.

Example

for (int I = 0; i< 10; i++)

{

//Action to be performed

}

  • While – As we can see in the example below the operation between the parenthesis will be performed over and over again till the evaluation of i>5 in true.

Example

While (i>5)

{

I = I -1;

}

  • If/else statements makes the decisions. As we can see in the example below the MessageBox will show the value if the variable yourValue is 3. The == sign that we see is for the evaluation and not assignment.

Example

If( yourValue == 3)

{

MessageBox.Show(“You were right”);

}