240 likes | 389 Views
BİL528 – Bilgisayar Programlama II. Variables. Contents. Variables. Variables. In your programs, you must determine the type of your data ( int , string , etc.)
E N D
BİL528 – Bilgisayar Programlama II Variables
Contents • Variables
Variables • In your programs, you must determine the type of your data (int, string, etc.) • In object oriented programming languages, you must also determine the level of visibility of your data (public, private, etc). • This visibility is known as scope.
Visual C# Data Types • In Visual C#, there are two categories of data types: • Value types • Reference types
Floating Value Types * Use decimal for currencies.
Type Casting • There are two types of type casting: Implicit and Explicit • Implicit conversions are done automatically by the compiler • Widening cast • No data loss • Example: conversion from float to double • Explicit conversions require programmers approval • Narrowing cast • Data may be lost • Example: conversion from double to float
Explicitly Converting Data • Simplest way is using C syntax: • double d = 2.3; • int i = (int) d; • You can also use Convert class: • double d = 2.3; • int i = Convert.ToInt32(d);
Declaring Variables • datatypevariable_name = initial_value; • int a; • string str = "BIM211"; • double m = 10, n = 20; • long k, l = 100; • Visual C# is a strongly typed language; therefore, you must always declare the data type of a variable. • In addition, Visual C# requires that all variables be initialized before they’re used.
Where to put variables? • Put variables in the class definition above the methods
Arrays • string[] strMyArray; • strMyArray = new string[10]; • Accessing elements: • strMyArray[0] = "BIM211"; • strMyArray[1] = "Visual Programming";
Multidimensional Arrays • int[,] intMeasurements; • intMeasurements = new int[3,2]; • Accessing elements: • intMeasurements[0, 0] = 1; • intMeasurements[2, 1] = 6;
Constants • You can define constant variables whose value can not be changed during the program execution by keyword const: • const double PI = 3.14159;
Exercise • Create a boolean variable to store whether a confirmation box appears or not • Change its value when “Confirm on exit” menu item is clicked • Handle the FormClosing event and write the following code: • (see next slide)
FormClosing Event if (m_blnPromptOnExit) { if (MessageBox.Show(“Close the Picture Viewer program?”, “Confirm Exit”, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { e.Cancel = true; } }
Arithmetic Operations • Arithmetic operations are same as C but you may prefer to read chapter 12 of the textbook.
String Operations • Length • SubString() • IndexOf() • Trim(), TrimStart(), TrimEnd(), Remove() • Replace()
Date/Time Operations • DateTime dateMyBirthday = new DateTime(2008,7,22); • AddDays(), AddHours(), etc. • ToLongDateString() • ToShortDateString() • ToLongTimeString() • ToShortTimeString()
Date/Time Operations • DateTime.Today • DateTime.Now