Is C # a safe language? How about my example

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

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 the result is 55.

+4
source share
4 answers

Yes it is. Your example uses var, which has a very different meaning in C # than it said in JavaScript. In C #, it is more like syntactic sugar. The code you wrote is equivalent to 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);
        }
    }
}

, , var, . , ( ), , .

, .

, , var , ...

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 re-purpose result to store an int
           result = 6;
           // or this
           result = intNum;
           Console.WriteLine(result);
        }
    }
}

(, JavaScript).

+1

, , , , , . .

+, , 7.8.4 # 4:

x + y (§7.3.4) . , - .

. , . , .

+4

:

  • # ? .

.

  1. , . , .

.
, var - , .

, , :

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

, .NET ​​ , . Concat.

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

, ToString .

+4

MSDN:

- , . ( .) , . , .

" " (JIT) Microsoft (MSIL) , JIT , , . , . . .

, . , . , , . , . , . , () . , , , . , , SecurityPermission SkipVerification .

Plus a short explanation :

If you ask what the term “safe type” means in general, this is a characteristic of the code that allows the developer to be sure that the value or object will have certain properties (that is, be of a certain type) so that he / she can use it in a certain way without fear unexpected or undefined behavior.

... and a detailed illustrative example of this URL.

0
source

Source: https://habr.com/ru/post/1674051/


All Articles