4

I am testing the following code in C# and it can be run successfully. My question is I can assign one type of data to another type of data in the following example, but why it is still called type-safe language? Thanks.

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;

    namespace Rextester
    {
        public class Program
        {
            public static void Main(string[] args)
            {
               var intNum = 5;
               var strNum = "5";
               var result = intNum + strNum;         
               Console.WriteLine(result);
            }
        }
    }

It can be compiled successfully and result is 55.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
user1232250
  • 329
  • 3
  • 19
  • 1
    Possible duplicate of [What is type-safe in .net?](http://stackoverflow.com/questions/2437469/what-is-type-safe-in-net) – ElektroStudios Apr 05 '17 at 04:27
  • http://stackoverflow.com/a/3398629/5621827 may help – jitender Apr 05 '17 at 04:28
  • No, my question is 1) is C# is a type safe language? Yes or No. 2) If the answer is yes, then why my code can be complied successfully. Does it mean my example does not relate to type-safe issue. Thanks. – user1232250 Apr 05 '17 at 04:34
  • Answer: Yes. Yes. – Sami Kuhmonen Apr 05 '17 at 04:56
  • http://stackoverflow.com/questions/10341188/string-concatenation-using-operator – Sarvesh Mishra Apr 05 '17 at 05:13
  • 2
    There's nothing 'type-unsafe' about having an operator overload that can work on disparate types. If you want to define a plus operator that works on a `Foo` and a `Bar` to create a `Baz` you can do that and it's still type-safe. – Ian Mercer Apr 05 '17 at 05:17

4 Answers4

6

To answer your repeated questions in the comments:

  1. is C# is a type safe language? Yes or No.

Yes.

  1. If the answer is yes, then why my code can be complied successfully. Does it mean my example does not relate to type-safe issue.

Your example does not relate to type-safe issue.
First note thatvar is just a syntactic sugar, the compiler will assign the right type to your variables based on the right side.

In other words, you're asking why the following is valid:

int intNum = 5;
string strNum = "5";
string result = intNum + strNum;
Console.WriteLine(result);

That is valid because .NET supports that kind of string concatenation, see the following Concat method.

string result = string.Concat(intNum, strNum);

The method concatenates both arguments by calling ToString method on them.

NixonUposseen
  • 53
  • 3
  • 12
4

type safe means it ensures that only operations permitted by type definition can be applied to the memory of the object, e.g. you can't cast an object to some incompatible type.

About the + operator concatenating a string and integer, this is specified in section 7.8.4 of the C# 4 spec:

For an operation of the form x + y, binary operator overload resolution (§7.3.4) is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined addition operators are listed below. For numeric and enumeration types, the predefined addition operators compute the sum of the two operands. When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands.

GorvGoyl
  • 42,508
  • 29
  • 229
  • 225
  • 1
    Thank you for your reply. However, can you simply answer my question below: 1) is C# is a type safe language? Yes or No. 2) If the answer is yes, then why my code can be complied successfully. Does it mean my example does not relate to type-safe issue. Thanks. – user1232250 Apr 05 '17 at 04:40
1

Yes it is. Your example uses var which has a very different meaning in C# than it has say, in JavaScript. In C# it is more of a syntatic sugar. The code you wrote is equivalent of the following -

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
           int intNum = 5;
           string strNum = "5";
           string result = String.Concat(intNum, strNum);         
           Console.WriteLine(result);
        }
    }
}

So basically, the compiler looks at the right side of a var declaration to decide on the right type. It's sort of telling the compiler to get the type (strictly compile time) because I am too lazy to bother with that.

But it serves a larger purpose, it lets you deal with anonymous types.

Finally, to demonstrate beyond any doubt that var is truly type safe, try the following code snippet...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
           var intNum = 5;
           var strNum = "5";
           var result = intNum + strNum;
           // Let's re-purpose result to store an int
           result = 6;
           // or this
           result = intNum;
           Console.WriteLine(result);
        }
    }
}

This is perfectly valid in a type agnostic language (again say JavaScript).

hazardous
  • 10,627
  • 2
  • 40
  • 52
0

From MSDN:

Type-safe code accesses only the memory locations it is authorized to access. (For this discussion, type safety specifically refers to memory type safety and should not be confused with type safety in a broader respect.) 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. For more information about verification, see Managed Execution Process.

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. Type-safe components can execute safely in the same process even if they are trusted at different levels. When code is not type safe, unwanted side effects can occur. For example, the runtime cannot prevent managed code from calling into native (unmanaged) code and performing malicious operations. When code is type safe, the runtime's security enforcement mechanism ensures that it does not access native code unless it has permission to do so. All code that is not type safe must have been granted SecurityPermission with the passed enum member SkipVerification to run.

Plus a shorter explanation:

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.

...and a in-depth illustrative example on that url.

Community
  • 1
  • 1
ElektroStudios
  • 19,105
  • 33
  • 200
  • 417
  • Probably would have been better to summarise that wall of text or at least **bold** the important bits –  Apr 05 '17 at 04:28