Is there an option to use the var keyword in the code cleaning settings in StyleCop and should I use the var keyword? [Closed]

Asked 2 years ago, Updated 2 years ago, 41 views

Do you want to improve this question?Update your question, Edit this post to be answered with facts and quotes.

Closed 7 years ago.

7 years ago

There is an option to use the var keyword in StyleCop's code cleaning configuration, but we are currently doing this internally.

Enter a description of the image here

I didn't set it up first, so I don't know why I always use Var.What we know is that the code is easy to read when using var.When I searched online, I found a similar question to stackoverflow headquarters

It's quite an interesting topic, so I'd like to hear opinions from domestic developers about whether the var keyword should always be used.

c#

2022-09-30 19:40

3 Answers

Personally, I use var regularly.
However, in the following cases, we are considering using an explicit type instead of an inference type.

1. As for the lambda expression, it is not possible to use var, so it will be written in one of the ways.

 varbinOp=(Func<int,int,int>)(x,y)=>x+y);
Func<int,int,int>binOp=(x,y)=>x+y;

Personally, I think the latter is more readable than the former, and it's easier to write because there are no extra brackets, so I don't often use var in the above case.

As for 2. I think that if you use it in the sample in the article, it will interfere with the viewer's understanding, so I often use it as clearly as possible.
However, if it is clear that literal has been replaced recently, I may use var, so this area is relatively loose and fluffy.

It's my personal feeling, but the influence around here is local, so if there are rules, I will follow them, and if there are no rules, wouldn't it be such a terrible thing?I think so.


2022-09-30 19:40

I don't think it's a good idea to bring in a locked question at home, but I'd like to mention a case where var is a regular user who doesn't use type reasoning.

  • When enumerating non-generic IEnumerable

Example) Windows Forms

foreach (Control c in Controls) // Type Inferable but castable
  • To reconfigure the value that you upcast later

Example) When searching the Entity Framework

IQueryable<Hoge>q=newSomeDbContext().TableHoge;//DbSet<Hoge>
if(fuga!=null)
    q=q.Where(_=>_.Fuga==fuga);//IQueryable<Hoge>
  • T and other short type names


2022-09-30 19:40

By default, always use the var keyword.
However, it is better to specify the type name exactly as it is than var for the type handling numbers, int, long, double, etc. Sometimes it's good.


2022-09-30 19:40

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.