2. C# Language Fundamentals Data Types Numeric Types Non-Numeric Types: char and bool Variables Definite Assignment Constants Strings Statements Code Samples
Data Types Common C# intrinsic data types Type Size in Bytes byte 1 bool 2 int 4 long 8 float double decimal 12
Typing in C# C# is a strongly typed language Types come in two flavours Value (intrinsic) Reference (classes …) Each type has a name (int) and size (4b) The .Net equivalents for int is Int32
Numeric Data Types Unsigned (positive) Signed (positive or negative) byte, ushort, uint, ulong Signed (positive or negative) short, int, long, float, decimal, double Select the smallest type that will hold the required range of numbers
Non-Numeric Types: char and bool Holds just a single character Can hold: Simple character (‘A’) Unicode character (u\0041) Escape character (‘\n’) bool Holds true or false in one byte
Declaring Local Variables int myInt; System.Console.WriteLine("Uninitialized, myInt: {0}",myInt); myInt = 5; int mySecondInt = 10; // declare and initialise int myInt4,myInt5; // declare multiple variables What is the value on an integer before it is initialised?
Declaring Constants Why would you create constants? const int FreezingPoint = 32; // degrees Farenheit const int BoilingPoint = 212; Why would you create constants?
Declaring Enumerations An enumeration is a set of named constants // declare the enumeration enum Temperatures:int { WickedCold = 0, FreezingPoint = 32, LightJacketWeather = 60, SwimmingWeather = 72, BoilingPoint = 212, } The data type defaults to int Why would you create enumerations?
Using Enumerations System.Console.WriteLine("Freezing point of water: {0}", (int) Temperatures.FreezingPoint ); System.Console.WriteLine("Boiling point of water: {0}", (int) Temperatures.BoilingPoint );
Declaring Strings A string is an object string myString = “Hello World” ;// declare and initialise string Where would you use strings in your code?
Statements, Expressions & White Space A statement ends in a semicolon int myInt = 23; An expression can be part of an assignment myInt = myInt * 23; White spaces are ignored myInt = myInt * 100;
Unit 2 Lab To write statements that prompt and greet the user 1. Open Visual Studio.Net and create a new C# Console Application project 2. In the Main method insert the following line: string myName; 3. Write a statement that prompts users for their name. 4. Write another statement that reads the user’s response from the keyboard and assigns it to the myName string. 5. Add one more statement that prints “Hello myName” to the screen (where myName is the name the user typed in). 6. Save your work.
Unit 2 Lab … When completed, the Main method should contain the following: static void Main( ) { string myName; Console.WriteLine("Please enter your name"); myName = Console.ReadLine( ); Console.WriteLine("Hello {0}", myName); }