Ultimate casting showdown: is vs. as

I know that many C# developers scratch their heads all the time, wondering how casting in really works and where lies the difference between the is and as keywords in C#.

Let’s dive in

To make this article easy to understand I won’t go into much detail.

For illustration purposes, imagine we have two classes – Car and Student. Obviously, these two classes do not belong to the same inheritance tree. All they have in common is that they both derive from System.Object. This piece of will be common for all upcoming examples.

Explicit casting

Now that we have declared the two objects, we can perform a casting operation. We will assign the student object to the car object. Unfortunately, this will fail. Using explicit casting, we will be informed about such problem by an InvalidCastException, which means the remaining Console.WriteLine statement won’t be executed.


If casting is valid, the car object will be assigned the value of the student object. Otherwise, it will have the value of null.

When using the as keyword, checks against the null value have to be carried out. This is done within the if statement. If all goes well, we should see “All went good” printed to the console.


As far as the is keyword is concerned, we have a pretty straightforward and type-safe approach to deal with casting.

Within an if statement we simply check if the cast would be valid. Following this check, we can proceed to explicit conversion, a.k.a. explicit cast.

This method, however, is quite inefficient, because at first we check the types and then carry out the cast. It’s true in situations when we know the cast will go through.

Expression bodied properties in C#

Today I would like to introduce you to an often disregarded feature of C# 6.0. As you might already know from the title, it will be about expression bodied properties.

Although, this revamped property initialization syntax has been around for 2 years, I see many developers still not making use of it.

Advantages of using expression bodied properties
Space consumption

I understand the competition for an additional kilobyte of memory is not really a thing nowadays, but when putting this feature in use, your source files will get smaller.


Since the body of your property is much more minimalistic, others might find it easier to get around in you code.

Example time!

I think a perfect example to demonstrate the use of expression bodied properties is the implementation of read-only properties.

We defined a private field _version , which is set to a version string within the SetVersion()  method. At the bottom, we have a Version property, which has a getter to return the version string. Very simple code…but could be even simpler.

This old way of getting stuff done can be replaced with this revamped code snippet.

It doesn’t really matter which way you choose. But sometimes there is no need to define a setter method in the body of a property. In such situations, the new syntax might come in handy.

C# 7.0: Tuples

Microsoft has recently unveiled some changes, that developers will be introduced to in the future release of C#, the C# 7.0.

Among all developers who see sharp 😀 , there is an enormous amount of anticipation of the features in the final release. In the meantime, I decided to interpret you one of them today. So let’s dive into it!

Tuples, I'm ready!
[1]: Tuples, I’m ready!

One of those things, that may please current developers and possibly attract new ones, are tuples. Tuples or tuple-like syntax can be found in many languages.

The universe before C# 7.0

In previous versions of C#, it could have been achieved this way using the out keyword when passing variables as parameters to a method:

This keyword allowed multiple values to be “returned” by the method. I am using apostrophes, because it is not really a tuple case-in-point and the GetTwoValues doesn’t really return any value, as well.

Getting closer…

This example in Python shows tuples the way they are commonly understood.

The example here is pretty straightforward and easy to understand. I personally haven’t been in a position wanting to return two or more values within a method, but is sure a step forward in the versatility of the C# language.

C# 7.0 at last

Let’s finally examine how tuples will look like in C# 7.0.

This sample works the same as the other one with out keywords shown earlier in the article. We get the values as elements in a tuple, store them into a variable of unknown type and then print them to the console. Each value is stored in the resulting container as an element called Item1 (Item2, Item3 and so on).

Item1 and Item2 is not overly descriptive. To avoid this woe, we can make use of named tuple elements. Let’s edit our code a bit.

The only, but important, change here is the switch from Item1 and Item2 to First and Second. Hence, making our code far more readible.

What do you think about C# 7.0 and tuples? Leave a comment down below.

Source: MSDN

Exceptions in C#

Imagine you are building a JSON parsing library in C# and the program crashes. You don’t want the user end up having no JSON file parsed and not knowing, what went wrong.

Figure 1: source

You are not that kind of a developer, are you?

Figure 2: source
So what are exceptions?

Exception is an event, that stops the execution of the program, due to some behavior, that you, as the programmer, cannot expect. In C#, all types of exceptions derive from the base Exception class in the System namespace.

Consider the following Console Application.

This for loop works well until the point, where the index reaches 4. At this point in time, the index would point to the 5th element in the array (since arrays start at index 0). But there are only 4 elements! This causes the .NET runtime to throw an IndexOutOfRangeException. When debugging the code in Visual Studio, this particular exception looks like this.

You’ve probably already met numerous third-party libraries (either as a developer or end-user), that use custom exceptions, but you never noticed. That is because there was no invalid operation to the program, which would cause the exception to be thrown. If there was and you would want the user to be informed pleasantly, you would have to use .NET exception handling.

.NET exception handling

In C#, the three most used keywords that enable this techique are  throw , try and  catch . They allow you to prevent an exception from completely stopping the program execution and leaving the user wondering, what happened.

For an unexpected behavior to be properly handled, it has to be caught (therefore the catch keyword).

To demonstrate this behavior, I will expand on the previous example. Consider this code.

The whole little “program” we made is inside the try block. Each time the for loop is successfully looped through, the number is written to the console. Then when the program gets to the critical index (see the example application description from So what are exceptions? paragraph for explanation), the catch block is executed. In this example, it would only get executed, when there was an IndexOutOfRangeException thrown. If there was a larger piece of code in the try block and it threw a FileNotFoundException, the program would crash just as any other program without exception handling.

Defining custom exceptions

When you are designing your own CLI compliant library, you can define you own set of exceptions, that best describe what went wrong.

When defining your own exceptions, they have to be placed into a class that inherits from System.Exception (this base class defines three constructors – a default constructor and two custom ones). They can all be created in your custom exception class, but have to call the respective base constructor.

Note: Exception classes should define as many constructors as possible.

An example would look like this.

When throwing CustomException somewhere in the code, you would do  throw new CustomException("Something doesn't work"); .

Dialogs in C# 101 – Opening and saving files

This tutorial will introduce you with the basics of using dialogs in C#.

These file operations are done using two classes:

  • OpenFileDialog – good for opening files using File Explorer dialog within the program
  • SaveFileDialog – good for saving files using File Explorer dialog within the program
Opening a file

To open a file, we will be using the OpenFileDialog class. This class allows you, as the programmer, to display a File Explorer dialog window. The user will be able to pick a file or multiple files and open them.

To open a file dialog in your program, you can use this snippet.

Let’s just briefly look at the code. The dialog variable represents an object of the OpenFileDialog class. The ShowDialog is a method that returns the dialog state after being closed. DialogResult is just an enumeration that represents each of the dialog states returned by the ShowDialog method. Then if the condition on the second line is true, our little program will display a MessageBox with the selected file’s path.

Saving file

To save a file, use this piece of code.

For the sake of demonstration, we created a variable dateAndTime that holds today’s date and current time. On the second line, we created an object of the SaveFileDialog class. In the if statement, we are checking if a directory and a file name is set. If that is true, then the current date and time is saved to a file.


The OpenFileDialog and SaveFileDialog classes are extremely powerful. In this part, we’ve shown how to open and close files using the File Explorer dialog window. In the next part, we will learn how to add file filters to the dialog.

Where are Windows Store apps located?

Some developers may be curious, where their apps are stored on their PCs after having been uploaded to Windows Store and then downloaded. Well the answer is quite simple.

All these apps are in a directory called WindowsApps (C:\Program Files\WindowsApps). By default this directory is hidden. To make it visible click on the View tab and then make sure Hidden item is checked.

Step 1
Step 1

Also access to this directory will probably be denied by default. To gain the required permissions do the following.

  1. Right-click the WindowsApps folder.
  2. Go to Properties.
  3. Select the Security tab.
  4. Then at the bottom of the window you should see an Advanced button. Click on it.
  5. In the new window click on Change.
  6. Write your account name into the last text box labeled Enter the object name to select.

After finishing this process, you should be able to access WindowsApps folder without any problem. If you still encounter any problem, feel free to ask me in the Comments section. I will answer as soon as possible.

NuGet 101

Many developers nowadays want their libraries public and widely used. For the ones of you developing libraries in C#, the best choice is NuGet.

What is NuGet?

NuGet is a package manager built into Visual Studio.

How to use NuGet?

There are two ways to download a package from NuGet. If you adore console-like interfaces, use a feature called Package Manager Console (Tools -> NuGet Package Manager -> Package Manager Console).

Package Manager Console
Package Manager Console

If you would rather use a GUI version of the Package Manager Console, click on Tools -> NuGet Package Manager -> Manager NuGet Packages For Solution.

For the purpose of this tutorial, I will use Package Manager Console. After opening the console, enter the following “Install-Package <package_name>”. Of course, in your case the <package_name> should be replaced with a valid package name (e.g. DZetko.Xml).

Package Manager Console
Package Manager Console

After hitting Enter, the package should start to install. This process may take a few seconds or minutes, based on the package size. If installation was successful, you should see “Successfully installed ‘<package_name>’ to <project_name>” as the last line of the console (once again with valid package name and project name).

How to publish packages to NuGet?

If you are a C# and you just finished your first library, then fire up your favorite browser and enter the following address  to download GUI version of NuGet Package Explorer. After the download and installation is complete, a window with a button should appear.

NuGet Package Explorer
NuGet Package Explorer

Then click on Create a new package or use the Ctrl + N keyboard shortcut. In the new window click on the little circled button.

Step 1
Step 1
Step 2

On the next screen fill the text boxes with bold labels next to them. Other text boxes are not required but you can fill them anyway. If you are not sure what some of the labels mean, please refer to this site.

Next step is very important, because we will be adding the .dll file into our package’s root. You can do so by dragging it from a folder where it is stored in, to the Package contents part of the NuGet Explorer window. A dialog will appear. Just click yes and the .dll file should now be shown in the lib folder in NuGet Package Explorer window.

Step 3
Step 3
Step 4

Your package is now complete. Only thing that’s left is to publish you library to NuGet. To do so, click on the green tick button on the left of the window. Then click on File -> Publish. A dialog will appear with an empty text box with Public key label. The key is a unique identifier which assigns every published package to your account. To obtain this key, navigate to http://nuget.org/ in your web browser and click on Register button under the search box. On the next page either sign-up with your Microsoft Account or fill-in required information on the bottom of the page to create a NuGet account. You will then recieve a confirmation e-mail. After the registration process is complete, sign-in and click on the button that says your name next to the Sign out button. On the next page, you should see an API key. Copy it over to the Publish Package dialog window of the NuGet Package Explorer. Then click the Publish button and wait until the process finishes. And you are done!

It will take a moment before the package is visible publicly.