Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Using var benefits
Message
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Environment versions
Environment:
C# 4.0
OS:
Windows XP SP2
Miscellaneous
Thread ID:
01512055
Message ID:
01512303
Views:
55
>>I'd argue that in some ways var makes code *less* portable since it is only accessible within the method where it is created - e.g it can't be used as a return value unless cast to a specific type. Of course you could resort to dynamic but I wouldn't want to go there unless absolutely neccessary :-}
>
>Eh... not so. This works fine:
>
>
>        public static string HelloWorld()
>        {
>            var text = "Hello World. Time is: " + DateTime.Now.ToString();
>            return text;
>        }
>
>
>The compiler fixes up var to its underlying type. The code is identical and you can definitely return a var local variable. You can't create var properties/fields of course, but for locals the behavior is just like typjng out the full name.

Well it works because you have explicitly defined the return type to be a string. No benefit there in not just using 'string text = ' in the first place - I'd consider that more readable? What about something like:
public static ?? PickSomePeople(List<Person> people)
    {
        var v = people
            .Select(p => new { p.Name, p.Age });
        return v;
    }
What return type can you use there except dynamic? Maybe it's a matter of taste - I'll stick to using var only for anonymous types,
Best,
Viv

>+++ Rick ---
>
>>
>>>The benefit of var is that it makes code more portable. If you don't explicitly type something and you later end up changing a type name or new type altogether but keep the interface the same the code still works without further changes to your code or refactoring.
>>>
>>>Under the covers the compiler does your work for you. It's a minor thing and I used to think it was better to use explicit types, but it saves a few short brain cycles and typing to do something like this:
>>>
>>>
>>>var items = new List<ChmImportItem>();
>>>
>>>
>>>instead of the duplication that is:
>>>
>>>
>>>List<ChmImportItem> items = new List<ChmImportItem>();
>>>
>>>
>>>No less clear what's happening but a bit less typing.
>>>
>>>+++ Rick ---
>>>
>>>>Hi all,
>>>>
>>>>Is there any performance benefits to using or not using var to declare objects?
>>>>
>>>>Is this better in some way (or not)
>>>>
>>>>DBRange range = new DBRange();
>>>>
>>>>over this:
>>>>var range = new DBRange();
>>>>
>>>>Thanks
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform