یا بهتر بود اسمه این تایپک رو میزاشتم Var چی هه؟

خوب حالا واقعا چی هه؟!

تعریفش میشه این عکسه پایین. کلا به جای هر تایپی میتونیم var بزاریم , و هر تایپی رو هم داشتیم میتونیم بریزیم توی var ، حالا بیایم یه کم بررسیش کنیم.

خوب میرسیم به اینجا که Var که خیلی خوبه بیایم برای راحتیه کار همه جا ازش استفاده کنیم و خلاص. ولی نههه، یه سری محدودیت داره:

این عکس رو از این مقاله گرفتم

حالا کجاها بهتره که ازش استفاده کنیم:

II. Object Creation via the _new_ Keyword
 
List<KeyValuePair<int,string>> niceList = new List<KeyValuePair<int,string>>();
 
var niceList = new List<KeyValuePair<int,string>>();

توی C# 9 هم میشه اینطوری نوشت و اینطوری دیگه حتی نمیخواد از var استفاده کنیم

List<KeyValuePair<int,string>> niceList = new();
 
### III. Explicit Type Conversions
 
var options = (JsonSerializerOptions)foo;

IV. When a Generic Parameter Controls the Results

Yes, this is wading a bit into non-obvious waters, as it consists of statements not being controlled by built-in keywords, but if the return type of a method is directly controlled via a generic type parameter, then you may feel free to use var.

var obviousReader = Activator.CreateInstance<StreamReader>();

V. When Enumerating a Local _IEnumerable T

If we have a local variable of type of IEnumerable<T>, we can more or less be assured that the object returned from enumerating it will be of type T.

IEnumerable<Type> types = FromSomewhere();
foreach (var type in types)
{
// Do stuff...
}

Although this too begins to dip its toes into the land of uncertainty, I feel that it’s acceptable to also use var if we’re accessing a local collection via an indexer or some other standard method. All within reason of course.

VI. When Assigning Another Local Variable or Method Parameter

If we need to declare a variable to hold a reference to another local variable or method parameter, there can be no doubt as to what that type is, so no harm in using var here as well.

IEnumerable<Type> types = FromSomewhere();
foreach (var type in types)
{
// To prevent closures from closing over a non-local variable.
var localType = type;
// Do some lambda stuff.
}

این قسمت رو هم از این سایته اوردم

Singleton.instance;

Copy

Singleton.instance;

Copy