Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is C# a type safe language? How about my example

Tags:

c#

typesafe

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.

like image 421
user1232250 Avatar asked Dec 24 '22 19:12

user1232250


1 Answers

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.

like image 126
NixonUposseen Avatar answered Dec 28 '22 05:12

NixonUposseen