Razor C# variables
ASP.NET Razor - C# Variables
Variables are named entities used to store data.
Variables
Variables are used to store data.
The name of a variable must start with an alphabetic character and cannot contain spaces or reserved characters.
A variable can be a specified type, indicating the type of data it stores. The string variable stores a string value ("Welcome to W3CSool.cc"), the integer variable stores a numeric value (103), the date variable stores a date value, and so on.
Variables are declared using the var keyword, or by using a type if you want to declare a type, but ASP.NET can usually determine the data type automatically.
Example
var greeting = "Welcome to W3CSchool.cc";
var counter = 103;
var today = DateTime.Today;
// Using data types:
string greeting = "Welcome to W3CSchool.cc";
int counter = 103;
DateTime today = DateTime.Today;
Data types
Commonly used data types are listed below:
Type | Description | Instance |
---|---|---|
int | Integer (all numbers) | 103, 12, 5168 |
float | floating point number | 3.14, 3.4e38 |
decimal | Decimal number (high precision) | 1037.196543 |
bool | Boolean value | true, false |
string | String | "Hello W3CSchool.cc", "John" |
Operators
Operators tell ASP.NET what commands to perform in an expression.
The C# language supports a variety of operators. Commonly used operators are listed below:
Operator | Description | Example |
---|---|---|
= | Assign a value to a variable. | i=6 |
+ - * / | plus a value or a variable . Subtract a value or a variable. Multiply a value or a variable. Divide by a value or variable. | i=5+5 i=5-5 i=5*5 i=5/5 |
-= | Variable increment. Variable is decremented. | i += 1i -= 1 |
are equal. Returns true if the values are equal. | if (i==10) | |
does not vary. Returns true if the values are not equal. | if (i!=10) | |
<= >= Less than. | more than the. Less than or equal to. greater or equal to. if (i<10) | if (i>10)if (i<=10) if (i>=10) |
Connection string (a series of related things). | "w3" + "schools" | |
Dot mark. Separate objects and methods. | DateTime.Hour | |
Parents. Group values. | (i+5) | |
Parents. Pass parameters. | x=Add(i,5) | |
square brackets. Access the values of an array or collection. | name[3] | |
Not. True/false negation. | if (!ready) | |
Logical AND. | Logical OR. if (ready && clear) | if (ready || clear)
Method | Description | Example |
---|---|---|
AsInt() IsInt() | Convert string to integer. | if (myString.IsInt()) {myInt=myString.AsInt();} |
IsFloat() | Convert string to floating point number. if (myString.IsFloat()) | {myFloat=myString.AsFloat();} |
IsDecimal() | Convert string to decimal number. if (myString.IsDecimal()) | {myDec=myString.AsDecimal();} |
IsDateTime() | Convert string to ASP.NET DateTime type. myString="10/10/2012"; | myDate=myString.AsDateTime(); |
Convert string to Boolean value. | myString="True"; | myBool=myString.AsBool();|
Convert any data type to character string. | myInt=1234; | myString=myInt.ToString();