1

I've just been looking at the templates in VS2013 for a new WebForms application. When I create a new site using the template, there is much code like this:

Dim requestCookie = Request.Cookies("SomeCookie")

Hovering over the requestCookie variable name, VS states that it is indeed a HttpCookie object type:

VS identifies object type

I haven't seen variables declared like that since VB6 (ASP classic). I see in the C# templates that the same approach is used. Also I see people using it a lot when writing C# code.

Is this a new approach or has it been 'valid' all this time? Is there any benefit to it other than less code?

I personally think it makes code harder to decipher and prefer explicitly setting the type: All the MSDN documentation regarding Dim shows As being used.

Dim requestCookie As HttpCookie = Request.Cookies("SomeCookie")
EvilDr
  • 8,943
  • 14
  • 73
  • 133
  • 2
    This is "type inference". The compiler has enough information to figure out the type. – John Saunders Jul 08 '14 at 14:12
  • Okay thanks John, but what's the actual benefit here, as per the question? Just less code? – EvilDr Jul 08 '14 at 14:13
  • 1
    The as statement is good when you're going to initialize the variable post-declaration. If you're going to initialize the variable immediately however, specifying the type seems unnecessary if the compiler is just going to infer the type anyway. – RageCage Jul 08 '14 at 14:19
  • 1
    http://stackoverflow.com/questions/3425966/what-advantages-does-using-var-have-over-the-explicit-type-in-c – djv Jul 08 '14 at 14:21
  • Thanks @DanVerdolino. The comments added to some of those answers provide interesting reading, especially the **lazy vs efficiency** angle – EvilDr Jul 08 '14 at 14:30
  • 2
    @EvilDr - if you want to use type inference and still have the compiler 'check things over' for you, look at the `Option Infer On` (or Off) statement, coupled with `Option Explicit`. – Grim Jul 08 '14 at 14:51

2 Answers2

2

This is "type inference". The compiler has enough information to figure out the type.

Sorry I don't have the VB.NET example handy:

var data = from c in context.Customers
           select new {c.Name, c.Address};

What's the type of data? The compiler knows. What if you change the expression?

var data = from c in context.Customers
           select new {c.Name, c.Address, c.Phone};

The compiler knows the new type. Now you don't have to change the type.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
1

Inferred Typing was a feature brought into the language (C# and VB) in the last couple of versions of the language in order to support anonymous typing via Linq. This is different from the old VB-Type dim-ing that created a Variant type.

An anonymous type is a shorthand way to pick only certain items from an object within a collection. For instance, consider the below:

dim users as new List<User>()
'...Code that adds users to the List here.

dim usernames = From U in users
                Select new with { .Username = U.Username }

This takes a list of users, and creates a new Enumerable with objects that just contain the Username. It's particularly useful as it can also be used to merge lists.

Additionally, some people advocate using it when it's not important for someone reading the code to know what the object is (i.e. what concrete class it is), but simply what it represents. Jon Skeets answer gives a decent coverage of this type of thinking. It's not really what Implicit Typing was designed for, but as always, developers find uses for things the designers never considered.

It's worth noting, that Inferred Typing (and anonymous typing) is purely a Design-Time conceit. Under the hood, during compile time, the Compiler will actually create a concrete class representing the anonymous type, and will code the variable to the hard coded type. You can confirm this by looking at the IL output for the exe:

Sub Main()

    Dim x = 5
    Dim y As Integer = 9

End Sub

Outputs to the IL as

.locals init ([0] int32 x,
       [1] int32 y)

You can see that it has initialised them as Ints. Equally, using an anonymous type:

Sub Main()

    Dim data As New List(Of Integer)({1, 2, 3, 4, 5})

    Dim y = From D In data
            Select New With {.Val = D, .Calc = D / 100}
End Sub

Causes the compiler to create a new Type inside the exe:

IL With Anonymous Type

And the Code to use this type:

 .locals init ([0] class [mscorlib]System.Collections.Generic.List`1<int32> data,
       [1] class [mscorlib]System.Collections.Generic.IEnumerable`1<class VB$AnonymousType_0`2<int32,float64>> y,
       [2] int32[] VB$LW$t_array$S0)
Community
  • 1
  • 1
Obsidian Phoenix
  • 4,083
  • 1
  • 22
  • 60
  • _brought back into the language_ - this implies that the feature existed before and was then removed and then _brought back_. Are you suggesting that type inference existed in the past or in prior versions of VB or C#? – Chris Dunaway Jul 09 '14 at 14:21
  • Ah no, I meant the syntax - Older VB allowed you to dim without type and essentially have it create as a `Variant` (I believe). I'll update the answer to remove the ambiguity – Obsidian Phoenix Jul 09 '14 at 15:40