Difference between the implementation of var in Javascript and C# - c#

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 = from mft in cars.Manufacturers
where mft.StockHeaders.Any(sh=> sh.StockCount>0)
orderby mft.CompanyName
select new {mft.CompanyID, mft.CompanyName};
// ...
Questions:
This code uses the var keyword. What is the benefit of this construct?
What is the key difference between the implementation of var in Javascript and C#?

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.

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#

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.

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);
}

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

Related

Reassigning weakly typed variable casting

Given that in C# we can have the weak type var which can be of any type until it's set, is it possible to have the same var change type depending on the output of a test?
For example
var c = DBQuery.FindString("paramater", "data");
this will return NULL if the query is unsuccessful or a string if it works.
From what I can see, as FindString is has a return type of string, var c is typed as a string, despite it being null.
Is there a way to unset the typing of c so that it can then be used for
var c = DBQuery.FindInt("parameter", "data2");
Thanks
The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.
The keyword you are probably looking for is dynamic. The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation.
Given this example
dynamic c = "foo";
Console.WriteLine(test.GetType());
c = 2;
Console.WriteLine(test.GetType());
Output
System.String
System.Int32
Nevertheless, I suggest you to adapt your code to avoid the dynamic type, mainly because you lose the ability to detect error at compile-time and the ability to use IntelliSense.
Additional resources
The var keyword: http://msdn.microsoft.com/en-us/library/bb384061.aspx
The dynamic keyword: http://msdn.microsoft.com/en-us/library/dd264736.aspx
You have understood the var keyword incorrectly. It's not any type until it's set. It's still statically typed.
It means: the compiler will figure out the type of the expression on the right-hand side of the assignement, and this will be the statically declared type of the variable.
Since DBQuery.FindString is declared as returning string (null or not), the declaration is 100% equivalent to:
string c = DBQuery.FindString("parameter", "data");
What you want to do is not possible in C#. You can declare the variable as object or dynamic and the code would work, but if you do so, you loose all design-time help such as IntelliSense (plus a runtime performance hit due to casting or dynamic typing).

Can you explan anonymous type in usage of using statement?

Can you explan anonymous type in usage of using statement? can you explan pros and cons two kind of usage?
using(var myCtx = new Entity() )
{
}
Another:
using(Entity myCtx = new Entity() )
{
}
What's the difference between them?
This is an implicitly typed variable, not an anonymous type. (An anonymous type is what you get using an expression such as new { X = 10, Y = "hello" }.
Your two code snippets are exactly equivalent - the compiler is just inferring the type of myCtx: it's still statically typed; the object will still be disposed etc.
There's nothing specific to the using statement here - you can use implicit typing for any local variable, so long as the type you want is the same as the compile-time type of the initialization expression. (If the value is null or an anonymous function, you'll need to cast the value, at which point it's reasonably pointless to use var, to be honest.)
Blatant plug: you can find out more details of both implicit typing and anonymous types in chapter 8 of my book, C# in Depth. Fortunately, that's one of the free chapter's you can download from the Manning page for the book.
There is no difference between the IL produced for both statements, they're functionally identical. What you're doing here is letting the compiler infer the type of myCtx, not creating an anonynous type. It can make code substantially clearer, for example:
var items = new Dictionary<int, Dictionary<int, string>>();
is clearer, and doesn't hide any of the intent of the code, than:
Dictionary<int, Dictionary<int, string>> items =
new Dictionary<int, Dictionary<int, string>>();
This isn't an anonymous type, it's jsut a syntax shortcut. As far as the compiler is concerned, the two statements are the same.
That's not actually anonymous type usage...it's inferred type usage. Using the var keyword simply "infers" the type on the left hand side of the assignment based on the right hand side of the assignment.
Pros:
Eliminates redundancy (eg. MyType a = new MyType() is highly redundant and unnecessary)
Cons:
Obfuscates the code when used in certain scenarios (eg. var a = GetSomething(); --- what type is a? I don't know without looking at the return type of GetSomething())
You lose the ability for polymorphism when using var (you can't have MyParentType a = new MySubType()) - this isn't really a con, so much as an invalid use case for the var keyword.
My rule of thumb is that I like the var keyword, but only use it where it's intent is already explicit...that is, I use it when using the new keyword, but not for foreach loops or assignments based on the return value of a method.

When should the var type be used in c#? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What’s the point of the var keyword?
What is the var type and should it be used in c#? When should it be used?
Can you specify the var type for the parameters to a method?
var is not a type. It is a convinient short hand notation that saves you a lot of typing. The following two declarations are equivalent:
Dictionary<string,List<int>> dic = new Dictionary<string,List<int>>();
and
var dic = new Dictionary<string,List<int>>();
As you can see, this saves typing and are easier to read. And if you descide to change the data type, you only have to change the right hand part.
But where I really like it most is in foreach loops:
foreach ( var item in someList )
Here item automatically takes the correct type, depending on the type of someList and it enables you to change the type of someList without haveing to change the declaration of item.
In short: var is GREAT and should be used.
EDIT: No, you can not specify var as a parameter to a function. The closest you can get to that is generics, I guess. And I also completely forgot to mention anonymous types. With those you have to use var.
It is part of the language, so yes, it should be used. It is not a type, however, but signifies a placeholder for the actual type determined by the compiler.
When should you use it? This has been asked before, many times:
Use of var keyword in C#
https://stackoverflow.com/questions/633474/c-do-you-use-var
var is not a type, it's an instruction to the compiler to let it figure out the correct type to use.
This means there is no difference at all to the output of the following two lines:
var s = "Test";
string s = "Test";
As for when to use it, you'll have to come up with your own rules. There is very few things you can do with var that you cannot do with a specific type name, but there is one thing: anonymous types.
You can do:
var x = new { A = 10 };
but you cannot come up with a strong type for that, since it has no type known at compile-time, instead the compiler will create the type during compilation, and then var will use that type.
That's what var was created to support, that it can also be used without anonymous types is a bonus, but you'll have to make up your own rules for when to use it in those cases.
Personally I only use it when the type is easily read from the source code, so I would use it for:
var dict = new Dictionary<int, string>();
var stream = new FileStream(...);
but not for:
var dict = GetDataStructure();
var stream = OpenFileForReading();
We tend to use it when interacting with all of our home grown libraries.
This is because we often change things as we are developing the libraries and quite often changing the type name or return type won't actually break the things which are using it.
We also tend to use it most of the time with the .NET framework as well.
However, we have put in an outright ban on using it with native types like int, string, bool etc. because it is not always clear what type the variable is in those cases.
Well, as mentioned earlier var is a short notation for a type name of any variable. As for me, I find, that var is overused by many developers and I think var makes code less readable sometimes. But one case where u should use it definitely is anonimous type variables.
Just to add to the other commentary, I suggest using var only when you can infer the type just by reading the code
var x = new Widget(); //ok
var y = Customer.Create(); // ok
var z = DoSomething(); //not ok
Some of the answers introduce Anonymous Types.
The var keyword on MSDN.
Know that var is not a type but a placeholder and can only be used within methods or properties (local variable definition). You can't use it in local member definition (private members of a class), neither can you when defining a method that should return whatever type, as generics, where you can use whatever name, except var (or any other reserved keyword) like so:
public IList<var> GetItems() { // Here the compiler will complain about the context of using `var` keyword within a local variable definition only.
}
public IList<T> GetItems() { // Here, we're talking about generics.
}
So, here are the principal rules to follow using the var keyword:
Local variable definition only;
Use var with anonymous types (Linq query, for instance);
Not to be confused with generic types;

How do you use the var keyword? [duplicate]

This question already has answers here:
Closed 13 years ago.
Duplicate
Use of var keyword in C#
C# - Do you use "var"?
Should I always favour implictly typed local variables in C# 3.0?
Would you prefer to write your code like this:
var myVar = new MyClass();
or
MyClass myVar = new MyClass();
I don't object to use the var keyword in example above; however, in the code below I don't like the usage of var.
var files = Files.GetFiles();
In this example it's not obvious what type variable files is going to be.
What's your preference for using the var keyword?
I tend to use 'var' in places where I, reading the sourcecode, can infer the type of the variable without having to navigate to other places in the sourcecode.
For example, any time I new up an object:
var c = new Customer();
Or when calling a method in which the return type is clear:
var c = Customers.GetCustomerByID(5);
Also, 'var' must be used in the case of anonymous types:
var t = new { Key = "One", Value = 1 };
And I also use it with LINQ of course:
var q = from c in Customers
where c.CustomerID == 5
select c;
In the case above 'q' is of type IQueryable (assuming Customers is an enumeration of Customer objects).
Also 'foreach' statements as well - GREAT please to use 'var':
foreach (var i in intArray) { /* use i */ }
Other examples abound I'm sure - but these cover my most frequent use cases.
If it's a situation where either would work (which excludes the anonymous type situation), I try to use whatever will make the code easier to understand in the future. Sometimes that means using var if the usage scope is small or the type being assigned to is unwieldy (e.g., somekind of nested generic) to repeat and adds clutter. I also tend to use var where most people expect to see (e.g. as the declaration of a linq query).
I think it's best to only use var when creating a new object (with new) and with LINQ (of course). That makes the code much easier to understand, IMHO.
I use it everywhere I can. I think it makes code far more clean and readable. (Who am I kidding? I just do what resharper tells me to do :)
Much more of that on this SO thread.

Does the new 'dynamic' C# 4.0 keyword deprecate the 'var' keyword?

When C# 4.0 comes out and we have the dynamic keyword as described in this excellent presentation by Anders Hejlsberg, (C# is evolving faster than I can keep up.. I didn't have much time to acquaint myself with the var keyword)
Would I still need the var keyword ? Is there anything that var can do.. that dynamic can't?
var x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
dynamic x = SomeFunctionThatIKnowReturnsSomeKindOfList();
// do something with x
No, they're very different.
var means "infer the type of the variable at compile-time" - but it's still entirely statically bound.
dynamic means "assume I can do anything I want with this variable" - i.e. the compiler doesn't know what operations are available, and the DLR will work out what the calls really mean at execution time.
I expect to use dynamic very rarely - only when I truly want dynamic behaviour:
var lets you catch typos etc at compile-time
statically bound code is always going to run faster than dynamically bound code (even if the difference becomes reasonably small)
statically bound code gives more compile-time support beyond just errors: you can find call hierarchies, refactoring will work better, Intellisense is available etc
Dynamic and var represent two completely different ideas.
var
Var essentially asks the compiler to figure out the type of the variable based on the expression on the right hand side of the assignment statement. The variable is then treated exactly as if it were explicitly declared as the type of the expression. For example the following two statements are equivalent
var a = "foo";
string a = "foo";
The key to take away here is that "var" is 100% type safe and is a compile time operation
dynamic
Dynamic is in many ways the exact opposite of var. Using dynamic is essentially eliminating all type safety for thet particular variable. It many ways it has no type. When you call a method or field on the variable, the determination on how to invoke that field occurs at runtime. For example
dynamic d = SomeOperation();
d.Foo(); // Will this fail or not? Won't know until you run the program
The key to take away here is that "dynamic" is not type safe and is a runtime operation
Yes you will still need var:
Var is a variable whose type will be inferred by the compiler.
dynamic will have its type assigned at runtime
So:
Var i = "Hello World"
will have its type inferred as a string type in doing so intellisence will give you all the methods that string can use like,
i.Split("/")
Where as:
dynamic i = "Hello World"
won't have its type inferred untill runtime because the complier dosn't know what type it is yet, but will still let you do:
i.Split("/")
but when it calls the method that you need it may fail because the type is wrong and the method isn't there.

Categories