C# is not type-safe

C# is usually touted as a type-safe language.  However, it is not actually fully type-safe!

To examine this claim, we must first provide a strict definition of type-safety  Wikipedia says:

In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behavior caused by a discrepancy between differing data types.

To translate this to C#, full type-safety means that any expression that compiles is guaranteed to work at runtime, without causing any invalid cast errors.

Obviously, the cast (and as) operator is an escape hatch from type safety.  It tells the compiler that “I expect this value to actually be of this type, even though you can’t prove it.  If I’m wrong, I’ll live with that”.  Therefore, to be fully type-safe, it must be impossible to get an InvalidCastException at runtime in C# code that does not contain an explicit cast.

Note that parsing or conversion errors (such as any exception from the Convert class) don’t count.  Parsing errors aren’t actually invalid cast errors (instead, they come from unexpected strings), and conversion errors from from cast operations inside the Convert class.  Also, null reference exceptions aren’t cast errors. 

So, why isn’t C# type-safe?

MSDN says that InvalidCastException is thrown in two conditions:

  • For a conversion from a Single or a Double to a Decimal, the source value is infinity, Not-a-Number (NaN), or too large to be represented as the destination type.

  • A failure occurs during an explicit reference conversion.

Both of these conditions can only occur from a cast operation, so it looks like C# is in fact type safe.

Or is it?

IEnumerable numbers = new int[] { 1, 2, 3 };

foreach(string x in numbers) 
    ;

This code compiles (!). Running it results in

InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

On the foreach line.

Since we don’t have any explicit cast operations (The implicit conversion from int[] to IEnumerable is an implicit conversion, which is guaranteed to succeed) , this proves that C# is not type-safe.

What happened?

The foreach construct comes from C# 1.0, before generics existed.  It worked with untyped collections such as ArrayList or IEnumerable.  Therefore, the IEnumerator.Current property that gets assigned to the loop variable would usually be of type object.   (In fact, the foreach statement is duck-typed to allow the enumerator to provide a typed Current property, particularly to avoid boxing). 

Therefore, you would expect that almost all (non-generic) foreach loops would need to have the loop variable declared as object, since that’s the compile-time type of the items in the collection.  Since that would be extremely annoying, the compiler allows you to use any type you want, and will implicitly cast the Current values to the type you declared.  Thus, mis-declaring the type results in an InvalidCastException.

Note that if the foreach type isn’t compatible at all with the type of the Current property, you will get a compile-time error (just like (string)42 doesn’t compile).  Therefore, if you stick with generic collections, you’re won’t get these runtime errors (unless you declare the foreach as a subtype of the item type).

C# also isn’t type-safe because of array covariance.

string[] strings = new string[1];
object[] arr = strings;
arr[0] = 7;

This code compiles, but throws “ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array.” at run-time.

As Eric Lippert explains, this feature was added in order to be more compatible with Java.

30 comments:

You are confusing type safety with static typing. "foreach" is typesafe as your post proves; an InvalidCastException is thrown at runtime, thus the C# runtime detected the type mismatch. The same is true of your array example.

I agree it would be nice if C# would detect the problem at compile time like a good statically checked language instead of pushing off some of these checks to the runtime, but as you point out, generics already fix most of these issues in practice.

It wouldn't suprise me if the compiler or tools like Resharper at least issues a warning.

No.

Static typing means that all expressions and variables have a defined type at compile-time. (unlike Javascript)

I'm describing compile-time type safety; you're talking about runtime type safety.

The above article is nice and interesting, thank you willing to share! Greetings success of admin Percetakan Murah Rawamangun Jakarta Timur wish you deign to visit my website, thank you :)

It's nice that you describe it.
one night



میثم ابراهیمی هوای دلیه
ماکان بند دلمو دزدید دانلود آهنگ های پرطرفدار جدید
محسن چاوشی شرح الف
پازل بند Memorable Podcast 4

There are very less people who know about type-safety programming and I was one of them. There were a lot of digital marketing companies that were in the demand of this coding, hence I started getting a lot of offers and I took few of them because it was a lot of money. I had to hire management assignment help services to give me the time to focus on that line of work.

Thank you so much for sharing all this wonderful information !!!! It is so appreciated!! You have good humor in your blogs. So much helpful and easy to read!
Visit to know more about Software Testing Course in Pune

This comment has been removed by the author.

Jee main preparation tips given by askIITians. It is must that a student make a time table for study. The right JEE Main preparation plan includes overall strategy,

neet online coaching

jee main preparation

cbse online classes

I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end.
Software Testing Course in Pune

إذا كنت لا تستطيع عمل ذلك أخي الكريم فما عليك إلا الإستعانة بخدمات شركة تنظيف خزانات تمتلك الخبرة الكافية لعمل تنظيف وتعقيم كامل للخزانات

Learn at Your Own Pace and Comfort Level
You won't have to modify your calendar to accommodate lessons if you take an online software testing course. You are also not need to travel to the classes. Furthermore, because these software testing training programmes emphasise self-learning, you will not feel left out. You may work through each idea at your own speed and communicate with your teachers to clarify concepts and issues.
Iteducation Centre is the top institute in Pune that provides a Software Testing Courses in Pune.

Nice information..Thanks for posting...
If you are searching for Artificial intelligence training in Pune, then the IT education center can be the best choice for you.

May be all these days I could not find any hacked code, Now I really need someone who can write and give Statistics thesis help with appropriate meaning of papers.

The child will interact with the tutor two or wow math four hours a week, and after that he must remain charged to do his own homework.

This comment has been removed by the author.

Thanks for the article it was such a nice information - Software Testing Classes in Pune

IT Education Centre provides advanced Java courses in Pune, Java Courses in Kolhapur, and other cities which is the perfect platform for all students. Java is a popular programming language for developing web applications. It enables a large number of programmers to write code using more efficient instruction sets supplied by Struts, the most popular framework for producing Java-based web software. The Apache Software Foundation developed Struts as an open-source project. The Struts framework is built on the Model View Controller (MVC) architecture. This frame connects the program’s Model with the Network View. An Action class is invoked when the Controller gets a petition. The Action class consults the Model to test or alter the program’s state. Also, you can refer to the following certification courses like Python Course in Kolhapur, Data science classes in Nagpur, and Data Science Course in Kolhapur.

This comment has been removed by the author.

IT Education Centre provides advanced Python courses in Pune, Python Course in KolhapurPython classes in Kolhapur, and other cities which is the perfect platform for all students. Java is a popular programming language for developing web applications. It enables a large number of programmers to write code using more efficient instruction sets supplied by Struts, the most popular framework for producing Java-based web software. The Apache Software Foundation developed Struts as an open-source project. The Struts framework is built on the Model View Controller (MVC) architecture. This frame connects the program’s Model with the Network View. An Action class is invoked when the Controller gets a petition. The Action class consults the Model to test or alter the program’s state. Also, you can refer to the following certification courses like Python Course in Kolhapur, Data science classes in Nagpur, and Data Science Course in Kolhapur.

Best Article i have read today. Well Informed and well written. Everyhing has organised and explained correctly.

Keep Updating these types of articles. There are plenty of websites who also provides the articles on Job Postings and Government Job Postings.

You can refer them here GovIntern.com

Useful post Thanks for sharing it that truly valuable knowledge about similar topic. python training in satara

Slak's Blog: Exploring the Intersection of Technology, Creativity, and Innovation. Stay tuned for insights, trends, and inspiration in the ever-evolving landscape of modern tech and creativity."
dui lawyer fairfax va
tax and estate lawyer
henrico traffic lawyer
virginia uncontested divorce

super slot ค่ายเกมสล็อตออนไลน์ที่เว็บ PGSLOT ของเรานำมาให้ลูกค้าทุกท่านได้เล่น เพื่อความสนุกสนานเพลิดเพลิน ที่มาพร้อมกับความปลอดภัย และรวดเร็วของแอดมินตลอดทั้งวัน

Keep up the thoughtful consideration of language features, and you'll continue to navigate C# with confidence and effectiveness! For visit: Professional business plan writer

Thank you for shedding light on this nuanced aspect of C# programming! Visit Vape pod systems

"True, C is not type-safe, which can lead to various programming errors and security vulnerabilities. While its flexibility and performance are advantageous, developers must exercise caution and implement rigorous testing and validation to mitigate risks. It's a reminder of the importance of choosing the right tool for the job."
Domestic Violence in New Jersey





Post a Comment