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.
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).