Type | Example |
---|---|
Integral types | sbyte, byte, short, ushort, int, uint, long, ulong, and char |
Floating point types | float and double |
Decimal types | decimal |
Boolean types | true or false values, as assigned |
Nullable types | Nullable data types |
<data_type> <variable_list>;Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas. Some valid variable definitions are shown here −
int i, j, k; char c, ch; float f, salary; double d;You can initialize a variable at the time of definition as −
int i = 100;
variable_name = value;Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as −
<data_type> <variable_name> = value;Some examples are −
int d = 3, f = 5; /* initializing d and f. */ byte z = 22; /* initializes z. */ double pi = 3.14159; /* declares an approximation of pi. */ char x = 'x'; /* the variable x has the value 'x'. */It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result. The following example uses various types of variables −
using System; namespace VariableDefinition { class Program { static void Main(string[] args) { short a; int b ; double c; /* actual initialization */ a = 10; b = 20; c = a + b; Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c); Console.ReadLine(); } } }When the above code is compiled and executed, it produces the following result −
a = 10, b = 20, c = 30
int num; num = Convert.ToInt32(Console.ReadLine());The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
int g = 20;But following is not a valid statement and would generate compile-time error −
10 = 20;
Cùng nhau học tập, khám phá các kiến thức nền tảng về Lập trình web, mobile, database nhé.
Nền tảng kiến thức - Hành trang tới tương lai hân hạnh phục vụ Quý khách!
Khám phá, trải nghiệm ngay
Vui lòng đăng nhập để gởi bình luận!
Đăng nhậpChưa có bình luận nào!