Use of Var Keyword in C#

Use of var keyword in C#

I still think var can make code more readable in some cases. If I have a Customer class with an Orders property, and I want to assign that to a variable, I will just do this:

var orders = cust.Orders;

I don't care if Customer.Orders is IEnumerable<Order>, ObservableCollection<Order> or BindingList<Order> - all I want is to keep that list in memory to iterate over it or get its count or something later on.

Contrast the above declaration with:

ObservableCollection<Order> orders = cust.Orders;

To me, the type name is just noise. And if I go back and decide to change the type of the Customer.Orders down the track (say from ObservableCollection<Order> to IList<Order>) then I need to change that declaration too - something I wouldn't have to do if I'd used var in the first place.

Usage of the C# var keyword

Which faster?

Neither, they're the same.

There is a dependence on the type?

I'm not sure what you're asking here, but there's no difference between any of those code snippets once they are compiled, so I'll go with no.

How much memory is allocated in both situation and when that memory allocated?

It's the same for all of them. For the int example it's 32 bits for all cases. For the List example all three will allocate one word for the reference, plus the memory for the actual list instance.

What's the point of the var keyword?

Update: There are two related questions here, actually:
1. Why do I have to declare variables at all?
2. What use is "var" in a language that makes you declare variables?

The answers to (1) are numerous, and can be found elsewhere for this question. My answer to (2) is below:

As other commenters have said, LINQ uses this for its anonymous types. However, LINQ is actually an instance of a more general problem where the type of the right-hand side of an expression is either unknown to the programmer, or is extremely verbose. Consider:

SomeGeneric<VeryLongTypename<NestedTypename>> thing = new   
SomeGeneric<VeryLongTypename<NestedTypename>>();

Verbose and error-prone, right? So now they let you do this:

var thing = new SomeGeneric<VeryLongTypename<NestedTypename>>();

By reducing the duplication of information, errors are eliminated. Note that there aren't just typing errors, here: it's possible for the type of the left-hand expression to be mistyped in such a way that the compiler can silently cast from left to right, but the cast actually loses some property of the rvalue. This is even more important when the types returned by the rvalue may be unknown or anonymous.

Is there is any way to use 'var' keyword against function Parameter?

the var in C# is very different from the var in other languages.

It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.

You cannot assign a var variable with null because in that case compiler will not be able to understand the type.

Similarly if you will not be able to return VAR from a method or will not be able to declare method parameter as Var because C# compiler will not be able to define the type of these things at compile time.

Please refer https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables

What does var mean in C#?

It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you cannot use the keyword var to declare field/property/parameter/return types.

Using listtype or var keyword difference

They are the same. var is implicitly typed.

If you hover over the keyword var in Visual Studio, it will show you the type of your object - in this case List<string>. The use of var is only to clean up code - you already know you're creating an object of type List<string>, so some people think it is redundant to type:

List<string> list = new List<string>();

There is no performance difference, as the compiler already knows what type the object is. Using var personal preference mostly - you can use it if you want to and there is no performance hit.

Eric Lippert has a great blog post about var here.

I think you're confusing var and dynamic, which are two totally different things. The dynamic type is a type that allows you to assign values of different types to it at runtime.

What is the equivalent of the C# 'var' keyword in Java?

There is none. Alas, you have to type out the full type name.

Edit: 7 years after being posted, type inference for local variables (with var) was added in Java 10.

Edit: 6 years after being posted, to collect some of the comments from below:

  • The reason C# has the var keyword is because it's possible to have Types that have no name in .NET. Eg:

    var myData = new { a = 1, b = "2" };

    In this case, it would be impossible to give a proper type to myData. 6 years ago, this was impossible in Java (all Types had names, even if they were extremely verbose and unweildy). I do not know if this has changed in the mean time.

  • var is not the same as dynamic. variables are still 100% statically typed. This will not compile:

    var myString = "foo";
    myString = 3;
  • var is also useful when the type is obvious from context. For example:

    var currentUser = User.GetCurrent();

    I can say that in any code that I am responsible for, currentUser has a User or derived class in it. Obviously, if your implementation of User.GetCurrent return an int, then maybe this is a detriment to you.

  • This has nothing to do with var, but if you have weird inheritance hierarchies where you shadow methods with other methods (eg new public void DoAThing()), don't forget that non-virtual methods are affected by the Type they are cast as.

    I can't imagine a real world scenario where this is indicative of good design, but this may not work as you expect:

    class Foo {
    public void Non() {}
    public virtual void Virt() {}
    }

    class Bar : Foo {
    public new void Non() {}
    public override void Virt() {}
    }

    class Baz {
    public static Foo GetFoo() {
    return new Bar();
    }
    }

    var foo = Baz.GetFoo();
    foo.Non(); // <- Foo.Non, not Bar.Non
    foo.Virt(); // <- Bar.Virt

    var bar = (Bar)foo;
    bar.Non(); // <- Bar.Non, not Foo.Non
    bar.Virt(); // <- Still Bar.Virt

    As indicated, virtual methods are not affected by this.

  • No, there is no non-clumsy way to initialize a var without an actual variable.

    var foo1 = "bar";        //good
    var foo2; //bad, what type?
    var foo3 = null; //bad, null doesn't have a type
    var foo4 = default(var); //what?
    var foo5 = (object)null; //legal, but go home, you're drunk

    In this case, just do it the old fashioned way:

    object foo6;

C# var keyword usage

I think it's fine to use var where it makes the code easier to read, which for me would mean that the type that var is replacing must be completely obvious.

For example, this would be a good use of var (contrived example):

var thing = new Dictionary<int, KeyValuePair<string, int>>();

However this would be a bad use of var:

var thing = GetThingFromDatabase();


Related Topics



Leave a reply



Submit