-3

I am studying code of my project and i came through 'var' keyword.I already know this that var keyword can store any data type.I want to understand how this happens.Also we already have object keyword to do this.Then why do we have var as well.We can achieve this using object keyword why to use var keyword.

CodeOfLife
  • 295
  • 2
  • 11
  • Read the question please.I want to understand how var works.I don't want to know the difference between object and var. – CodeOfLife Feb 18 '19 at 13:17
  • @Amrendra next time you post a question please take your time to come up with a useful title rather than some content of the actual question. – Felix D. Feb 18 '19 at 13:21
  • @Amrendra Did you read the other question (and answer)? In what way is it different from the question you are asking? Which part of your question isn't answered by the answer? – Luaan Feb 18 '19 at 13:26
  • What is going on is what is known as **type inference**. You can think of **var** as a place holder where a type is actually filled in by the compiler/interpreter and that type is the resulting type of the right-hand operand of the assignment. – inquam Feb 18 '19 at 13:27
  • @Luaan i got my answer from below answer and also from "What does var mean in c#".Please delete the question if it's possible to. – CodeOfLife Feb 18 '19 at 13:33

2 Answers2

1

var is not a type - it's a shortcut. The type of the actual variable is determined at compile-time. Compare:

var number = 42;
number = "42"; // Compilation error! You can't assign a string value to an integer variable

and

object number = 42;
number = "42"; // No problem - someNumber used to be an instance of the type (boxed) Int32, 
               // and now is of type string. The type of the variable is still just object.

In the first case, the variable declaration is equivalent to saying int number = 42;. The type is determined based on the type of the right value, in this case, an integer literal. When you try to work with the variable in some way (e.g. number + 10), the variable behaves as any other integer variable.

In the second case, the type of the variable is object. It can store any value available in C# at any time. Even if the variable contains a value of type integer, it still behaves as a plain object (e.g. number + 10 is a compile-time error, because there's no + operator defined between object and int).

Luaan
  • 62,244
  • 7
  • 97
  • 116
0

var actually cannot, as you mention, store any object. Initially you can assign any type, but you cannot change into another type later on.

var is more for the "lazy" developer who does not explicitly want to state which type the created object will be, and would rather let the IDE/compiler see which type the var will be, by looking at whatever is stored in it. (Ok, as per the comments, not always necessarily lazy. But for arguments sake, I'm calling it lazy.)

In this example: var foo = "bar";

the IDE will simply see that we are going to put a string into bar. So it will know that var will be string.

You will not be able to do foo = 12; later on in the same block, as foo is a string.

In Visual Studio you can actually ctrl+. on the var keyword, and request Visual Studio to change the var keyword into string.

This implicitly means you cannot create a var without directly assigning anything to it, as the IDE will not be able to infer the type, such as in only var foo;

nl-x
  • 11,762
  • 7
  • 33
  • 61
  • 1
    Lazy? Hardly. It's been designed for types that cannot be represented in the C# code's text (e.g. anonymous types). There's plenty of strong-typed languages that don't expect you to laboriously type out the type of the local when it's assigned. Is typing `System.String foo = "bar";` preferable to `string foo = "bar";`? Is the latter just being "lazy"? :) Also, it's not the IDE that determines the type, it's the compiler. – Luaan Feb 18 '19 at 13:25
  • 3
    "var is just for the lazy developer that does not explicitly want to state which type the created object " That's just plain wrong. `var` was introduced with the concept of anonymous types - so you could do `var x = new {A = 1, B = 2};`. Also, as a side effect, it can help to make the code more readable by eliminating the need to repeat long, tedious type names (`var x = new Dictionary>>();`) – Zohar Peled Feb 18 '19 at 13:27
  • @ZoharPeled: I would argue that your mentioned "side effect" is actually one of the main reasons behind using it as a developer. Then you have other usages that the compiler and library authors etc benefit from when type inference exists. But as a "regular joe" long wielding types or for instance in C++ iterators of objects with already long and complex signatures or lambdas and/or function pointers, it's great. Using it since it's shorter than writing *std::string" would not be a good enough reason in my book :) – inquam Feb 18 '19 at 13:33
  • I will put lazy in quotation marks, as `var` is sometimes indeed the only way to create a variable, as with said anonymous types. But honestly, in over 90% of its uses, people just use `var` to avoid having to hardcode the type of the variable, even when they could do so. – nl-x Feb 18 '19 at 13:33
  • And sometimes it's better to have the type hardcoded, and sometimes the opposite is better. In the end, it's a style preference. As for laziness, why would we ever have software in the first place if we weren't lazy? Laziness is what shapes all the life on the planet, as well as human progress. Just don't confuse "save a bit of time now, pay the price later tenfold" and "invest a little time now, save a lot of time later". Thrift is a virtue. Unless there's a point to writing it out, why write it out? :) – Luaan Feb 18 '19 at 13:45