Type Safe in C#

In general,  it is the characteristic of code that allows the developer to be certain that a value or object will exhibit certain properties (i.e., be of a certain type) so that developer can use it in a specific way, he/she can directly convert it into a certain data type object and don’t have to worry about any kind of behavior.

Example:

Let’s take an example of generic collection List of type int.

        List<int> objIntList = new List<int>();
        objIntList.Add(1);
        objIntList.Add(2);

In your code you can directly cast the value from any index into Int e.g

        int intVal =  (int) objIntList[0];

Type safe make sure that whatever value that object is holding is of same type in case of collection.

Let’s take another example using ArrayList to understand the non type safe object. As we know that ArrayList can contains objects of different types.

If we run the below code

        var integers = new ArrayList();
        integers.Add(1);
        integers.Add(2);
        integers.Add("3");

        for (int i = 0; i < integers.Count; ++i){
            int integer = (int)integers[i];
        }

Framework will throw the  Invalid Cast Exception i.e. “Specified cast is not valid.” for index value at 2, because “3” is added as string in ArrayList and string cannot be cast to int.

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s