Is C# a strongly typed or a weakly typed language?


Presented as a dialogue, as is my wont!

Is C# a strongly typed or a weakly typed language?

Yes.

That is unhelpful.

I don’t doubt it. Interestingly, if you rephrased the question as an “and” question, the answer would be the same.

What? You mean, is C# a strongly typed and a weakly typed language?

Yes, C# is a strongly typed language and a weakly typed language.

I’m confused.

Me too. Perhaps you should tell me precisely what you mean by “strongly typed” and “weakly typed”.

Um. I don’t actually know what I mean by those terms, so perhaps that is the question I should be asking. What does it really mean for a language to be “weakly typed” or “strongly typed”?

“Weakly typed” means “this language uses a type verification system that I find distasteful“, and “strongly typed” means “this language uses a type system that I find attractive“.

No way!

Way, dude.

Really?

These terms are meaningless and you should avoid them. Wikipedia lists eleven different meanings for “strongly typed”, several of which contradict each other. Any time two people use “strongly typed” or “weakly typed” in a conversation about programming languages, odds are good that they have two subtly or grossly different meanings in their heads for those terms, and are therefore automatically talking past each other.

But surely they mean something other than “unattractive” or “attractive”!

I do exaggerate somewhat for comedic effect. So lets say: a more-strongly-typed language is one that has some restriction in its type system that a more-weakly-typed language it is being compared to lacks. That’s all you can really say without more context.

How can I have sensible conversations about languages and their type systems then?

You can provide the missing context. Instead of using “strongly typed” and “weakly typed”, actually describe the restriction you mean. For example, C# is for the most part a statically typed language, because the compiler determines facts about the types of every expression. C# is for the most part a type safe language because it prevents values of one static type from being stored in variables of an incompatible type (and other similar type errors). And C# is for the most part a memory safe language because it prevents accidental access to bad memory.

Thus, someone who thinks that “strongly typed” means “the language encourages static typing, type safety and memory safety in the vast majority of normal programs” would classify C# as a “strongly typed” language. C# is certainly more strongly typed than languages that do not have these restrictions in their type systems.

But here’s the thing: because C# is a pragmatic language there is a way to override all three of those safety systems. Cast operators and “dynamic” in C# 4 override compile-time type checking and replace it with runtime type checking, and “unsafe” blocks allow you to turn off type safety and memory safety should you need to. Someone who thinks that “strongly typed” means “the language absolutely positively guarantees static typing, type safety and memory safety under all circumstances” would quite rightly classify C# as “weakly typed”. C# is not as strongly typed as languages that do enforce these restrictions all the time.

So which is it, strong or weak? It is impossible to say because it depends on the point of view of the speaker, it depends on what they are comparing it to, and it depends on their attitude towards various language features. It’s therefore best to simply avoid these terms altogether, and speak more precisely about type system features.

Comments (36)

  1. Eric says:

    Excellent post, as usual.

    "C# is not as strongly typed as languages that do enforce these restrictions all the time."

    Can anyone mention here some of these languages.

  2. C. McCann says:

    My favorite definition is that how "strongly typed" a language is measures the degree to which circumventing type restrictions is considered bad coding practice by its programming community.

    This definition has the advantages of being completely orthogonal to static typing (and every other feature of a type system), of aligning well with many informal uses of the term, and of being patently absurd as a way of describing languages.

  3. Sukru says:

    @Eric: ADA comes to mind. They have a very strict type system (A string of length 5 is not assignable into a string variable of length 6, for example).

  4. lukas99 says:

    @Eric

    Not sure, but maybe Haskell? No pointersunsafe mode. No dynamic. No casting (?).

  5. Jesse C. Slicer says:

    "as is my wont!" –  It must have taken a lot of strong typing to add such an excellent phrase that is often underutilized in today's discourse.

  6. Erik Hesselink says:

    While I would classify Haskell as perhaps more 'strongly' typed than C#, there are still ways to get around its typing discipline. There are dynamic types (Data.Dynamic), casts, both safe (Data.Typeable.cast) and unsafe (Unsafe.Coerce.unsafeCoerce), and pointers (mostly used for interfacing with C).

  7. MgSm88 says:

    You left out anything about the "dynamic" keyword/type. I think maybe for the public at large's sake (as your blog is often regarded as a definitive source on C#) that you should mention dynamic and how it throws an additional wrench into the picture.

  8. masklinn says:

    > Not sure, but maybe Haskell? No pointersunsafe mode. No dynamic. No casting (?).

    Technically, Haskell has a whole host of unsafe "modes": http://www.haskell.org/hoogle the parent of all unsafe* being unsafePerformIO which allows bypassing the IO monad and performing IO from anywhere (which may completely crash the runtime, or result in very wacky behavior, such as the IO code being called a million times in a second due to STM). Casts and pointers are part of the unsafe* stuff (unsafeCoerce, unsafe*Ptr).

    There are also dynamic types: hackage.haskell.org/…/Data-Dynamic.html but they're kind-of safe (see fromDyn and fromDynamic)

  9. dharmatech@live.com says:

    Hi Eric,

    My question isn't actually in relation to this posts topic, although I will mention a "dynamically typed" language… 🙂 Not sure where else to direct questions to you.

    Message cascades were recently added to the Dart programming language:

    news.dartlang.org/…/method-cascades-in-dart-posted-by-gilad.html

    Was just wondering, is it in the realm of possibility for these to appear in a future version of C#? Or is there something in their design which makes them incompatible with C#?

    I like that folks would no longer have to design their APIs to be "fluent". I have a personal library of extension methods for making WPF more fluent (github.com/…/FluentWpf). Message cascades in C# would eliminate the need for things like FluentWpf.

    Message cascades also appear to make object initializer syntax (new Obj() { abc = 10 }) unnecessary (although I realize, that's here to stay).

    Thanks for any insight!

    Signed,

    Envious of Dart programmers right now

  10. Brennan Falkner says:

    @dharmatech Visual Basic has that.

    msdn.microsoft.com/…/wc500chb.aspx

  11. DBJDBJ says:

    Eric : "…C# is a pragmatic language …"

    DBJ : Is C++ "a pragmatic language" ?

  12. Mike says:

    What do you think about the term Manifest vs. Latent typing?

  13. Chris Eargle says:

    "C# is for the most part a type safe language because it prevents values of one static type from being stored in variables of an incompatible type."

    Unless you use StructLayout.Explicit and define two fields with incompatible types and the same FieldOffset value.

  14. nicolas.pietrzak@hotmail.com says:

    And sometimes it depends on the C# grammar 🙂

    -> enum test : int // COMPILES

    -> enum test2 : System.Int32 // DOES NOT COMPILE (integral-type expected)

  15. RP says:

    @Chris Eargle: I guess you missed the *for the most part* bit.

  16. bmm6o says:

    MgSm88: It's in the penultimate paragraph.

  17. leppie says:

    Not sure I agree that C# is ever weakly typed (without tedious user intervention).

    Can you show an example of what you mean?

    PS: My normal criteria for a weakly typed language is "if it looks like a number, it can be one, no matter the backing type".

  18. Christopher says:

    I think C++ is the same thing. It is type-safe but also allows casts. Seems like a lot of languages are "strongly-typed" AND "weakly-typed."

  19. Is the gist of today's blog that strongly/weak typing is a Partial-Ordering?

  20. vbscript2 says:

    leppie, That just demonstrates Eric's point about how "strongly-typed" and "weakly-typed" don't have widely-accepted definitions. Personally, to avoid confusion, I would propose using the term "horribly-typed" to refer to the languages that fit your criteria of "weakly-typed." 🙂

  21. Jimmy says:

    Pythonistas will often say Python is a strongly (yet dynamically) typed language, meaning type conversion is usually explicit. If x = 5 and y = "foo", then in C#, x + y yields "5foo" whereas Python doesn't allow the implicit string-conversion (well, in a statically typed language, it's merely sugar, but in a dynamic language, it can lead to ambiguity)

  22. JMCF125 says:

    I've been hearing these type definitions for a long time, but I never completelly understood them until now.

  23. info@modelospr.com says:

    Is C# a strongly typed or a weakly typed language?

    Well, it depends how hard I hit the keyboard keys when I'm programming.

    🙂

  24. Jeff Lewis says:

    Not suprisingly (given that this is a question of semantics), you're playing a bit of a semantic game here.

    The argument seems to be 'Since I can get around C#'s type enforcement, it's not really a strongly typed language'.. which is like arguing that since I can remove the brakes in my car, clearly the car is inherently unsafe. It's *technically* true, but only when you consider the worst cases, rather than the typical and ignores the notion of 'intent'.

    Oddly, I thought you were going to go in a different direction – and argue that the dynamic extensions to C# render it weakly typed (ie: var, but as we all know, var isn't actually var). 'Object' is a better example of that dynamic nature – but it's been around since the start.

    To most programmers, I believe, the term 'strongly typed' means "the compiler expects me to know the types for variables and data and get them right at compile time, not deferring it to run time unless I explicitly tell the compiler I'm doing something weird – otherwise, it will say 'no'". That may not be a formal definition – but it's certainly how most people use the term.

    So is C# strongly typed? Best answer I have is 'most of the time'.

  25. melnakeeb says:

    Great Article. C# doesn't enforce these 3 safety systems all time but only most time, but this can allow risky developers to get performance gain in performance critical jobs. Java enforce these safety systems all time , but usually this drop performance making applications as eclipse and netbeans much slower than monodevelop and sharpdevelop, with no way out to increase performace.

  26. melnakeeb says:

    @  Commentor Eric:

    Java is strongly typed that do enforce these restrictions all the time.

    1-Java doesn't allow any use of pointers at all, no  way to override this with "unsafe"

    2-Java doesn't allow "dynamic"

    but java is weakly typed as :

    1-It removes type information from generics in compile time (type erasure) since java 5 but type information will be reserved to be checked during runtime starting from java 8 insha'Allah

    On the other hand C# is reserving type info in generics for runtime checking since .net 2

    2- Java as c# allow cast operators

  27. hirendra_sisodiya@live.com says:

    what the means of type verification and type system here?

  28. Douglas says:

    @Jeff Lewis: A car *is* inherently unsafe!

    When you take a ton of steel, add in a dozen gallons of highly combustible liquid, then intentionally detonate that liquid thousands of time per minute to propel the vehicle to high speeds, what you get is definitely unsafe.

  29. raceprouk@hotmail.co.uk says:

    @Jimmy: In C#, 5 + "foo" is (effective) shorthand for String.Format("{0}foo", 5), or maybe String.Format("{0}{1}, 5, "foo"). Either way, it's not actually an overload on +.

    </pedant> 😉

  30. Starnick says:

    Interesting read. At the end I was imagining Eric as Obi-wan Kenobi in "Return of the Jedi", when he was talking about it depends on your point of view regarding Darth Vader.

  31. Anonymous says:

    c# i think is a weakly typed language i.e it will find some loophole to do some implicit type conversion for nearly matching types' input arguments.

  32. Rudra Bhattacharya says:

    Excellent post,Nice and subtle approach to define what makes C# strongly typed

  33. Louis.fr says:

    @Jimmy: In C#, 5 + "foo" does not imply a conversion to string. The operator+(object,string) is invoked. When compiled, you'll get a call to string.Concat(object,object). Still no conversion to string. In either case (operator+ or string.Concat), the arguments don't need to be converted to string.

  34. JP says:

    Eric;

    Was wondering what your thoughts were on this article?

    steve-yegge.blogspot.com/…/execution-in-kingdom-of-nouns.html

  35. default_ex says:

    It's hard to call C# strongly typed when you can do things like the following:

    uint i = unchecked((uint)-1);

    [StructLayout(LayoutKind.Explicit)] struct SomeStruct

    {

       [FieldOffset(0)] float SomeFloat;

       [FieldOffset(0)] byte SomeByte;

    }

    ulong SomeFunc(ulong i)

    {

        fixed (ulong* p = i) return (ulong)Interlocked.Read(*(long*)p); // there is no ulong overload for this

    }

    Among many other techniques to read data as a type that it clearly is not.

  36. nikosv says:

    the "Weakly Typed Languages" article at

    http://www.i-programmer.info/programming/theory/1469-type-systems-demystified-part2-weak-vs-strong.html?start=1

    and the "Strong Typing" one at

    http://www.i-programmer.info/programming/theory/1515-strong-typing.html

    (parts of the "Type Systems Demystified" series at

    http://www.i-programmer.info/programming/theory/604-type-systems-demystified.html)

    attempt to explain the differences between weak and strong typing by comparing the type systems of Perl,C# and VB.NET and how C#'s dynamic type changes the game (especially in the "C# Perl-like behavior?" section). Although very educational (I hope),the point of the articles is to show that in the end "These terms are meaningless and you should avoid them" as you have already pointed out