CSharp – Variables and Data Types
Data types
You are required to inform the compiler about which data types you wish to use every time you declare a variable.
byte —> 0 .. 255
sbyte —> -128 .. 127
short —> -32,768 .. 32,767
ushort —> 0 .. 65,535
int —> -2,147,483,648 .. 2,147,483,647
uint —> 0 .. 4,294,967,295
long —> -9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807
ulong —> 0 .. 18,446,744,073,709,551,615
float —> -3.402823e38 .. 3.402823e38
double —> -1.79769313486232e308 .. 1.79769313486232e308
decimal —> -79228162514264337593543950335 .. 79228162514264337593543950335
char —> a Unicode character.
string —> a string of Unicode characters.
bool —> true or false.
object —> an object.
Example with strings:
// Working with strings using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // <datatype> <name> string firstName = "John"; string lastName = "Doe"; Console.WriteLine("Name: " + firstName + " " + lastName); Console.WriteLine("Please enter a new first name:"); // get new value from console firstName = Console.ReadLine(); Console.WriteLine("New name: " + firstName + " " + lastName); Console.ReadLine(); } } }
Example with math:
// Working with math using System; namespace ConsoleApplication1 { class Program { static void Main() { // integer numbers int number1, number2; Console.WriteLine("Please enter a number:"); // It reads a string and converts it into an integer. number1 = int.Parse(Console.ReadLine()); Console.WriteLine("Thank you. One more:"); number2 = int.Parse(Console.ReadLine()); Console.WriteLine("Adding the two numbers: " + (number1 + number2)); Console.ReadLine(); } } }
Constants
The constants refer to fixed values that the program may not alter during its execution.
The syntax is:
const <data_type> <constant_name> = value;
Example:
using System; using System.Collections; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { const double pi = 3.14159; // constant declaration double r; Console.WriteLine("Enter Radius: "); r = Convert.ToDouble(Console.ReadLine()); double areaCircle = pi * r * r; Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle); Console.ReadLine(); } } }