62

What is type-safe?

What does it mean and why is it important?

Braiam
  • 1
  • 11
  • 47
  • 78
Surya sasidhar
  • 29,607
  • 57
  • 139
  • 219
  • possible duplicate of [What is Type-safe?](http://stackoverflow.com/questions/260626/what-is-type-safe) – Braiam Apr 23 '15 at 13:14

5 Answers5

81

If you're asking what the idea of "type-safe" in general means, it's 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 he/she can use it in a specific way without fear of unexpected or undefined behavior.

For instance, in C#, you could say the ArrayList class is not type-safe because it can store any object, which means you can do something like the following:

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];
    // do something
}

The above will compile because the value "3", even though it's a string and not an integer, can legally be added to an ArrayList since String derives (like Int32) from Object. However, it will throw an InvalidCastException when you try to set integer to (int)integers[2] because a String cannot be cast to an Int32.

On the other hand, the List<T> class is type-safe for exactly the opposite reason--i.e., the above code would not compile if integers were a List<int>. Any value that you the developer access from within a type-safe List<int> you can be certain is an int (or whatever the corresponding T is for any generic List<T>); and you can therefore be sure that you'll be able to perform operations such as casting to int (obviously) or, say, long.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • I disagree with you. ArrayList is neither type-safe nor not type-safe: http://stackoverflow.com/a/17984521/1145224 . – Anton Lyhin Feb 02 '16 at 22:52
  • 4
    he is just trying to explain the importance of type checking, he didn't mean to explain about array list characteristics. – clarifier May 21 '17 at 14:24
15

C - You declare an int, cast it to char and access memory beyond int's boundary

int i = 10;
char *s = (char*)i;
print(*(s+10));

C# - Types are safe

int i = 10;
char *s //This is invalid unless you are using unsafe context. 

Pointers are not directly supported by .NET

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
A9S6
  • 6,575
  • 10
  • 50
  • 82
  • +1 TypeSafe is something relevant to memory access by CLR or program, instead of focusing TYPES. Hence +1 for this response as it is targeting the actual difference. REF: http://www.exforsys.com/tutorials/csharp/.-net-type-safety.html – Sumeet May 09 '11 at 06:57
  • C without strange cast is *type safe* (all standards except very ancient). Your sample isn't strict in this area. You speak ... can say ... about memory safe / unsafe solutions ??? C# with strange cast can be type-unsafe in normal sections ("non unsafe"): positive compilation, error on runtime – Jacek Cz Sep 25 '15 at 06:29
  • @JacekCz No. Type safety is a specialization of Memory safety and C is not even memory safe since you can have buffer overflows like you want, silent stack overflows, no exceptions preventing false behaviour, including undefined behaviour for different operators. C has a weak type system. Even C's pointers are not memory safe since you can do pointer arithmetic. Whatever language can cause use-after-free bugs and doesn't define initialization values for local variables, is not type safe. – ChrisoLosoph Jul 12 '22 at 21:45
10

Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.

During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification

Although verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

For more refer msdn link

A good article explaining it is here

supi
  • 2,172
  • 18
  • 15
HotTester
  • 5,620
  • 15
  • 63
  • 97
-1

Did you mean type-safe in particular or type-safety in general?

I disagree with the accepted answer: ArrayList is type-safe ignorant (neither type-safe nor not type-safe): https://stackoverflow.com/a/17984521/1145224

Richter - CLR via C#, 4th edition (page 93):

Type-safety is the main feature of CLR. You can always discover object's exact type by calling nonvirtual GetType method of the System.Object.

For example Hero class can not override GetType method to become a type of SuperHero.

This System.Object feature enables CLR to check the possibility of casting objects at runtime. For example:

internal class Employee { ... }

public sealed class Program 
{

    public static Main() 
    {
        DateTime dt = new DateTime(2016, 1, 1);
        PromoteEmployee(newYears);
    }

    public static PromoteEmployee(Object o)
    {
        Employee e = (Employee)o; //InvalidCastException, runtime error
    }
}

Casting DateTime type to Employee type is an example of a not type-safe attempt to cast.

Community
  • 1
  • 1
Anton Lyhin
  • 1,925
  • 2
  • 28
  • 34
  • I think, it is considered type safe as long as it doesn't allow you to do undefined or unexpected things. Type-Safety generally cannot be achieved by compile-time analysis alone (since bounds checking is a subset which requires solving the halting problem). The most practical approach is, to have runtime checking and fail retrospectively (via exception, still better than crashing or misbehaving), if something is wrong. Sometimes, "upcasting" is valid, sometimes not. You could forbid this kind of cast in your definition of type safety, but there would be no good reason to exclude it. – ChrisoLosoph Jul 12 '22 at 21:56
-2

I don't agree with some answers here. C# has few levels of safety.

EDIT: Type safety has 2 levels of meaning (if we generally discus about programming languages, as in this thread)

One is compile time type-safety, near to refactoring etc, compiler catch typos, misspelled assigning of values to wrong variables (properties), i.e. string to int variable. Typical C# code is type-safe, known way to disable this feature is dynamic keyword, or non generic containers, errors like above are delayed to runtime. Example: non-hacking C/C++ code is (generally) type safe at compile time. I think is possible write (hacking) casting in C# which hide type conflicts.

Next level is runtime type-safety, C# is safe in general (without unsafe sections). Even dynamic value are checked on runtime. In contrast: C/C++ isn't type safe at runtime. If compiler accept code, un-logical assigning isn't checked at runtime, providing bizarre / strange / system level or late errors, typical for C language.

Few of answerers in this thread mix other areas where C# is safe (memory safety, range safety, null pointer etc). To be strict, these are different kind of safety.

Theory: https://en.wikipedia.org/wiki/Type_safety

Jacek Cz
  • 1,872
  • 1
  • 15
  • 22
  • Your "compile-time type safety" is called semantic analysis. Confused people maybe call it "static type safety". They probably think of code without exceptions but it makes no sense since you don't obtain program correctness or expected functionality at runtime with this "static type safety" alone, particularly because of pointers and NULL. And why calling it statically type-safe, if the language permits violation? Static type satey would be weaker than memory safety or otherwise static type safety would not be turing complete. Static Type safety also requires defined default initialization. – ChrisoLosoph Jul 12 '22 at 22:24