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.
To answer your repeated questions in the comments:
Yes.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With