Difference between the implementation of var in Javascript and C#

后端 未结 5 743
情深已故
情深已故 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<SomeTypeTheCompilerCreatedOnTheFly>. 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.

    0 讨论(0)
  • 2020-12-29 21:05

    The only thing they have in common is that they are used to declare local variables.

    The C# equivalent of JS var is dynamic. But since most C# users prefer static typing it is usually only used in interop scenarios of some kind(with COM or a dynamically typed language).

    C# var still uses static typing, but with an inferred type. Since JS only supports dynamic typing, there is no equivalent.

    In this context explicit static typing isn't possible, since new {mft.CompanyID, mft.CompanyName} creates an anonymous type, so implicit static typing with var is used.

    0 讨论(0)
  • 2020-12-29 21:06

    var in C# is dynamic at design time but staticly typed at compile time. You will see that if you do:

    var mftQuery = from mft in cars.Manufacturers
        where mft.StockHeaders.Any(sh=> sh.StockCount>0) 
        orderby mft.CompanyName
        select new {mft.CompanyID, mft.CompanyName};
    

    and then:

    mftQuery = "Hello world!";
    

    It will not compile and complain about missmatching types even though you didn't specify any type.

    This is a useful productivity enhancement because you can easily change return types to similar types without breaking anything and it is easier to write. A stupid example:

    foreach(var animal in GetCats()){
       Console.WriteLine(animal.Owner);
    }
    

    could be changed to:

    foreach(var animal in GetDogs()){
       Console.WriteLine(animal.Owner);
    }
    
    0 讨论(0)
  • 2020-12-29 21:09

    And to answer your question 1, the benefit of using var keyword in the presented code is at may be difficult to come up with the resulting type for the LINQ query and can be easily affected by the change to the query. In fact, its introduction to C# coincide with the premiere of LINQ.

    Reassuming, it is to make the life of programmer easier and also to remove the redundancy of Type t = new Type().

    0 讨论(0)
  • 2020-12-29 21:22

    a) C#'s var lets you avoid writing an explicit type upon variable declaration. This makes your code more compact, also sometimes the type of the expression on the right side of the declaration is complicated and in the same time you are not interested what the actual type is.

    b) Javascript's var is like C#'s dynamic. It lets you declare a variable but you can change its type.

    var i = 1; 
    i = "foo";  // legal in Javascript, illegal in C#
    
    0 讨论(0)
提交回复
热议问题