id.ot
id.ot

Reputation: 3131

LINQ to XML type declaration

If we're using C# (LINQ to XML) to loop through nodes contained in a small (< 100kb) XDocument object is it a better practice or better performance-wise to use XElement or the standard implicit "var" type?

Illustrated:

foreach (XElement el in node.Elements())
{
    ...
}

or

foreach (var el in node.Elements())
{
    ...
}

Upvotes: 1

Views: 190

Answers (2)

Jan P.
Jan P.

Reputation: 3297

This does not change anything. var is just a short form for developers to write shorter code. While compiling it will be revamped back to XElement in your case.

var is strongly typed! Please do not understand var like a type free variable in PHP.

An example:

PHP

$i = 3;
$i = new MyObject();
//Everything is fine

C#

var i = 3;
i = new MyObject();
//compiler error!

So there is no difference between

var i = 3;

and

int i = 3;

After compiling var is anyways replaced by int, so there will be no better performance while execution.

Upvotes: 4

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

There is no difference for performance, because type inference in .NET occurs on compile time. All variables will be strongly typed after compilation.

Also there is no rule for usage var or type name for variable declaration. It's a matter of personal preference. Some people like to see type of variable they working with, some people consider type declaration as form of duplication (not case for foreach statement, but for simple variable declaration).

Real power of var goes when you are working with anonymous types (that's why it was introduced). You simply can't specify type name of variable:

var people = from p in doc.Descendants("Person")
             select new { p.Name, p.Id };

Consider reading Implicitly Typed Local Variables article.

Upvotes: 1

Related Questions