Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Use of var in Xamarin.forms

ScottHalpernScottHalpern USMember ✭✭
edited June 2015 in Xamarin.Forms

I'm new to C#, so forgive me for the basic question.

I am working through the Xamarin.Forms introduction and I noticing that the view objects are declared using var vs. the explicit type. Is there any specific reason for this? Just so the code looks cleaner?


Example from the introduction:

var listView = new ListView
RowHeight = 40
listView.ItemsSource = new string []
"Buy pears",
"Buy oranges",
"Buy mangos",
"Buy apples",
"Buy bananas"
Content = new StackLayout
VerticalOptions = LayoutOptions.FillAndExpand,
Children = { listView }

Why not declare listView like so:
ListView listView = new ListView
RowHeight = 40



  • RyanDavisRyanDavis AUInsider, University ✭✭
    edited June 2015

    Hi @OzHalpern

    Yes, by now it is definitely idiomatic of C# (that is, not just Xamarin.Forms) to declare local variables using var, for at least these reasons:
    - saves repeating yourself and reduces noise in the code
    - makes refactoring later easier - less parts of your code to change
    - saves you from having to type out complex types, like those that can result from LINQ expressions.

    In general, if you see examples or projects explictly specifying the type of local variables, it's likely that they are quite old. Of course, you will still find people every now and then who oppose the use of var and avoid it whenever possible!

  • FredyWengerFredyWenger CHInsider ✭✭✭✭✭

    You will find both variants in the examples...
    I'm coming from and had some problems, to become familiar with c#.
    I'm still no "specialist" but am able to code with it now (and am on the way to release my first XF-app to the shops) :smile:
    With the time, you will find your way, how to do it...

    As it seems that you are relatively new to Xamarin...
    I have wrote a starter guide some time ago, which should be useful for you. It contains concentrated information's you don't will find this way else (including also e.g. how to format code in a message :wink: ) You can find it here:

    Hope this helps you further and... good luck :sunglasses:

  • ScottHalpernScottHalpern USMember ✭✭

    @FredyWenger Thanks for that! I come from native iOS and Android development. I will deifnitely work through your resource!

  • ScottHalpernScottHalpern USMember ✭✭

    @RyanDavis Thanks! That definitely makes sense. The code looks a lot cleaner. Appreciate the answer.

Sign In or Register to comment.