Difference between the implementation of var in Javascript and C#

后端 未结 5 744
情深已故
情深已故 2020-12-29 20:33

I would like to ask a theoretical question. If I have, for example, the following C# code in Page_load:

cars = new carsModel.carsEntities();

var mftQuery =          


        
5条回答
  •  一生所求
    2020-12-29 21:04

    JavaScript is a dynamically typed language, while c# is (usually) a statically typed language. As a result, comparisons like this will always be problematic. But:

    JavaScript's var keyword is somewhat similar to C#'s dynamic keyword. Both create a variable whose type will not be known until runtime, and whose misuse will not be discovered until runtime. This is the way JavaScript always is, but this behavior is brand new to C# 4.

    dynamic foo = new DateTime();
    foo.bar();  //compiles fine but blows up at runtime.
    

    JavaScript has nothing to match C#'s var, since JavaScript is a dynamically typed language, and C#'s var, despite popular misconception, creates a variable whose type is known at compile time. C#'s var serves two purposes: to declare variables whose type is a pain to write out, and to create variables that are of an anonymous type, and therefore have no type that can be written out by the developer.

    For an example of the first:

    var conn = new System.Data.SqlClient.SqlConnection("....");
    

    Anonymous type projections from Linq-to-Sql or Entity Framework are a good example of the second:

    var results = context.People.Where(p => p.Name == "Adam")
                                .Select(p => new { p.Name, p.Address });
    

    Here results is of type IQueryable. No matter how much you might like to write out the actual type of results, instead of just writing var, there's no way to since you have no knowledge of the type that the compiler is creating under the covers for your anonymous type—hence the terminology: this type is anonymous

    In both cases the type is known at compile time, and in both cases, subsequently saying either

    conn = new DateTime();
    

    or

    results = new DateTime();
    

    would result in a compiler error, since you're setting conn and results to a type that's not compatible with what they were declared as.

提交回复
热议问题