Easy Tutorial
❮ Met Websecurity Getcreatedate Met Websecurity Login ❯

ASP.NET Razor - C# Variables


Variables are named entities used to store data.


Variables

Variables are used to store data.

A variable name must start with a letter character and cannot contain spaces or reserved characters.

Examples


Data Types

The following table lists common data types:

Type Description Examples
int Integer (whole 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 tutorialpro.org", "John"

Operators

Operators tell ASP.NET what commands to perform in an expression.

C# supports various operators. The following table lists common operators:

Operator Description Example
= Assigns a value to a variable. i=6
+ <br>- <br>* <br>/ <br> Adds a value or variable. <br>Subtracts a value or variable. <br>Multiplies a value or variable. <br>Divides a value or variable. i=5+5 <br>i=5-5 <br>i=5*5 <br>i=5/5
+= <br>-= Increments the variable. <br>Decrements the variable. i += 1 <br>i -= 1
== Equality. Returns true if values are equal. if (i==10)
!= Inequality. Returns true if values are not equal. if (i!=10)
< <br>> <br><= <br>>= Less than. <br>Greater than. <br>Less than or equal to. <br>Greater than or equal to. if (i<10) <br>if (i>10) <br>if (i<=10) <br>if (i>=10)
+ Concatenates strings. "run" + "oob"
. Dot. Separates objects and methods. DateTime.Hour
() Parentheses. Groups values. (i+5)
() Parentheses. Passes parameters. x=Add(i,5)
[] Brackets. Accesses array or collection values. name[3]
! Not. Inverts true/false. if (!ready)
&& <br> Logical AND. <br>Logical OR. if (ready && clear) <br>if (ready clear)

Converting Data Types

Converting from one data type to another can be useful.

Generally, user input is treated as a string, even if the user enters numbers. Therefore, numeric input must be converted to a number before it can be used in calculations.

The following table lists common conversion methods:

Method Description Example
AsInt() <br>IsInt() Converts a string to an integer. if (myString.IsInt()) <br>{myInt=myString.AsInt();}
AsFloat() <br>IsFloat() Converts a string to a float. if (myString.IsFloat()) <br>{myFloat=myString.AsFloat();}
AsDecimal() <br>IsDecimal() Converts a string to a decimal. if (myString.IsDecimal()) <br>{myDec=myString.AsDecimal();}
AsDateTime() <br>IsDateTime() Converts a string to an ASP.NET DateTime type. myString="10/10/2012"; <br>myDate=myString.AsDateTime();
AsBool() <br>IsBool() Converts a string to a boolean. myString="True"; <br>myBool=myString.AsBool();
ToString() Converts any data type to a string. myInt=1234; <br>myString=myInt.ToString();
❮ Met Websecurity Getcreatedate Met Websecurity Login ❯