var มีไว้เพื่อกำหนดตัวแปรโดยไม่ต้องประกาศ data type โดยที่ var จะดูจากค่าที่เราใส่ให้กับตัวแปรนั้นๆของเราว่าค่านั้นจะเป็น data type อะไร และยังช่วยให้เราเขียนโค้ดให้สั้นลง และ มีความหยืดหยุ่นด้วย
ตัวอย่าง เช่น
publicclassGFG {staticpublicvoidMain(){var a =50;var b ="Welcome! Geeks";var c =340.67d;var d =false;Console.WriteLine("Type of 'a' is : {0} ",a.GetType());Console.WriteLine("Type of 'b' is : {0} ",b.GetType());Console.WriteLine("Type of 'c' is : {0} ",c.GetType());Console.WriteLine("Type of 'd' is : {0} ",d.GetType());}}
Type of 'a' is : System.Int32
Type of 'b' is : System.String
Type of 'c' is : System.Double
Type of 'd' is : System.Boolean
**การใช้ var จะต้องใส่ค่าให้ตัวแปรนั้นๆด้วย ไม่สามารถใส่ null ได้ เพราะจะทำให้เกิด errorได้**
การเปรียบเทียบการใช้ var ของ C# กับ Java , Python , C
Java ต้องใช้เป็น Java10 ถึงจะสามารถลองรับการใช้ var ได้
การใช้คำสั่ง var ใน Java10 มีความคล้ายกับการเขียน ใน C# แต่มีความแตกต่างกันตรงที่
ใน Java จะใช้ได้แค่ใน local variables แต่ของ C# มีความหยืดหยุ่นในการใช้มากกว่า
public static void main(String[] args)
{
// int
var x = 100;
// double
var y = 1.90;
// char
var z = 'a';
// string
var p = "tanu";
// boolean
var q = false;
// type inference is used in var keyword in which it
// automatically detects the datatype of a variable
System.out.println(x);
System.out.println(y);
System.out.println(z);
System.out.println(p);
System.out.println(q);
}
}
name = "Educative"
gender = "Female"
money = 10000
print("Name is", name, "type of variable is", type(name))
print("Gender is", gender, "type of variable is", type(gender))
print("Gender is", money, "type of variable is", type(money))
Out put
Name is Educative type of variable is <class 'str'>
Gender is Female type of variable is <class 'str'>
Gender is 10000 type of variable is <class 'int'>
ไม่มีการรองรับ var ต้องมีการกำหนดชนิดของตัวแปรนั้นๆก่อนที่จะเอาไปใช้งาน เพราะในภาษา C ไม่มี dynamic typing เหมือนใน Python จึงทำให้ต้องประกาศชนิดตัวแปรก่อนเสมอ
#include <stdio.h>
int main() {
int x = 10;
float y = 3.14;
char z = 'A';
printf("x: %d\n", x); // พิมพ์ค่า x
printf("y: %.2f\n", y); // พิมพ์ค่า y (2 ตำแหน่งทศนิยม)
printf("z: %c\n", z); // พิมพ์ค่า z
return 0;
}