Neal Stublen C# Data Types Built-in Types  Integer Types byte, sbyte, short, ushort, int, uint, long, ulong  Floating Point Types.

Slides:



Advertisements
Similar presentations
Operators & Identifiers The Data Elements. Arithmetic Operators exponentiation multiplication division ( real ) division ( integer quotient ) division.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
CS1061 C Programming Lecture 5: Building Blocks of Simple Programs A. O’Riordan, 2004.
C programming an Introduction. Types There are only a few basic data types in C. char a character int an integer, in the range -32,767 to 32,767 long.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2: Introduction to C++.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Basic Elements of C++ Chapter 2.
Section 2 - More Basics. The char Data Type Data type of a single character Example char letter; letter = 'C';
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
CSC 125 Introduction to C++ Programming Chapter 2 Introduction to C++
Neal Stublen Tonight’s Agenda  C# data types  Control structures  Methods and event handlers  Exceptions and validation  Q&A.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Primitive Data Types and Operations Identifiers, Variables, and Constants Primitive Data Types Byte, short, int, long, float, double, char, boolean Casting.
1 Chapter 2 Primitive Data Types and Operations F Introduce Programming with an Example  The MyInput class F Identifiers, Variables, and Constants F Primitive.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Simple Data Types and Statements. Namespaces namespace MyNamespace { // …. { MyNamespace::func1() using namespace OtherNamespace; Comments: // /* xxxx.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 3A Integral Data (Concepts)
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
STATEMENTS AND FLOW OF EXECUTION CHAPTER 11 OF APRESS A PROGRAMMERS GUIDE TO C SHARP 5.0.
Data & Data Types & Simple Math Operation 1 Data and Data Type Standard I/O Simple Math operation.
C++ Programming: Basic Elements of C++.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CECS 121 Test 1. Functions allow you to group program statements under one name C and C++ are case-sensitive so main(), MAIN(), and Main() are all different.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 2: Introduction to C++
Computer Engineering 1 st Semester Dr. Rabie A. Ramadan 3.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
CSCI 3328 Object Oriented Programming in C# Chapter 4: C# Control Statement – Part I 1 Xiang Lian The University of Texas Rio Grande Valley Edinburg, TX.
C# C1 CSC 298 Elements of C# code (part 1). C# C2 Style for identifiers  Identifier: class, method, property (defined shortly) or variable names  class,
CECS 130 EXAM 1. To declare a constant (read only) value: const int x = 20; const float PI = 3.14; Can we do this? const int x;
Data Types Declarations Expressions Data storage C++ Basics.
Programming with Visual C++: Concepts and Projects Chapter 3A: Integral Data (Concepts)
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
Java Programming, Second Edition Chapter Two Using Data Within a Program.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1.2 Primitive Data Types and Variables
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP Basics.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
ITK 168 – More Variables 10/13/05. Another example of using instance variables and constants  Go through SimpleBot  Modify SimpleBot to “teleport”
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Chapter 3 The New Math. C++ Data Types simple integral charshort intlong bool floating float double Long double enum address pointer reference structured.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Basic Introduction to C#
C# and the .NET Framework
© 2016, Mike Murach & Associates, Inc.
Multiple variables can be created in one declaration
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
Based on Murach’s Chapter 4
Basics of ‘C’.
Chapter 2: Basic Elements of Java
Module 2: Understanding C# Language Fundamentals
Data Types Imran Rashid CTO at ManiWeber Technologies.
Module 2 Variables, Data Types and Arithmetic
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Neal Stublen

C# Data Types

Built-in Types  Integer Types byte, sbyte, short, ushort, int, uint, long, ulong  Floating Point Types float, double, decimal  Character Type char (2 bytes!)  Boolean Type bool ( true or false )  Aliases for.NET data types (Byte, Integer, Decimal, etc.)

Declare and Initialize ; int index; float interestRate; = ; int index = 0; float interestRate = ;

Constants const = ; const decimal PI = ;

Naming Conventions  Camel Notation (camel-case) salesTax Common for variables  Pascal Notation (title-case) SalesTax Common for type names and constants  C or Python style sales_tax (variable) SALES_TAX (constant) Not common

Arithmetic Operators  Addition (+)  Subtraction (-)  Multiplication (*)  Division (/)  Modulus (%)  Increment (++)  Decrement (--)

Assignment Operators  Assignment (=)  Addition (+=)  Subtraction (-=)  Multiplication (*=)  Division (/=)  Modulus (%=)

Type Casting  Implicit  Less precise to more precise  byte->short->int->long->double int letter = 'A'; int test = 96, hwrk = 84; double avg = test * hwrk * 0.2;

Type Casting  Explicit  More precise to less precise  int->char, double->float ( ) double total = 4.56; int avg = (int)(total / 10); decimal decValue = (decimal)avg;

What Should Happen? int i = 379; double d = 4.3; byte b = 2; double d2 = i * d / b; int i2 = i * d / b;

"Advanced" Math Operations  totalDollars = Math.Round(totalDollars, 2);  hundred = Math.Pow(10, 2);  ten = Math.Sqrt(100);  one = Math.Min(1, 2);  two = Math.Max(1, 2);

Strings  string text = "My name is ";  text = text + "Neal"  text += " Stublen."  double grade = 94;  string text = "My grade is " + grade + “.”;

Special String Characters  Escape sequence  New line ("\n")  Tab ("\t")  Return ("\r")  Quotation ("\"")  Backslash ("\\")  filename = "c:\\dev\\projects";  quote = "He said, \"Yes.\"";  filename  quote said, ""Yes.""";

Converting Types .ToString(); .Parse( );  Convert.ToBool( );  Convert.ToString( );  Convert.ToInt32( );

Formatted Strings .ToString( );  amount.ToString("c"); // $43.16  rate.ToString("p1"); // 3.4%  count.ToString("n0"); // 2,345  String.Format("{0:c}", 43.16); // $43.16  String.Format("{0:p1}", 0.034); // 3.4%  See p. 121 for formatting codes

Variable Scope  Scope limits access and lifetime  Class scope  Method scope  Block scope  No officially "global" scope

Enumeration Type enum StoplightColors { Red, Yellow, Green }

Enumeration Type enum StoplightColors { Red = 10, Yellow, Green }

Enumeration Type enum StoplightColors { Red = 10, Yellow = 20, Green = 30 }

Enumeration Type enum StoplightColors { Red = 10 } string color = StoplightColors.Red.ToString();

"null" Values  Identifies an unknown value  string text = null;  int? nonValue = null;  bool defined = nonValue.HasValue;  int value = nonValue.Value;  decimal? price1 = 19.95;  decimal? price2 = null;  decimal? total = price1 + price2;

Control Structures  Boolean expressions Evaluate to true or false  Conditional statements Conditional execution  Loops Repeated execution

Boolean Expressions  Equality (==) a == b  Inequality (!=) a != b  Greater than (>) a > b  Less than (<) a < b  Greater than or equal (>=) a >= b  Less than (<=) a <= b

Logical Operators  Combine logical operations  Conditional-And (&&) (file != null) && file.IsOpen  Conditional-Or (||) (key == 'q') || (key == 'Q')  And (&) file1.Close() & file2.Close()  Or (|) file1.Close() | file2.Close()  Not (!) !file.Open()

Logical Equivalence  DeMorgan's Theorem  !(a && b) is the equivalent of (!a || !b)  !(a || b) is the equivalent of (!a && !b)

if-else Statements if (color == SignalColors.Red) { Stop(); } else if (color == SignalColors.Yellow) { Evaluate(); } else if (color == SignalColors.Green) { Drive(); }

switch Statements switch (color ) { case SignalColors.Red: { Stop(); break; } case SignalColors.Yellow: { Evaluate(); break; } default: { Drive(); break; }

while Statements while (!file.Eof) { file.ReadByte(); } char ch; do { ch = file.ReadChar(); } while (ch != 'q');

for Statements int factorial = 1; for (int i = 2; i <= value; ++i) { factorial *= i; } string digits = "" for (char ch = '9'; ch <= '0'; ch-=1) { digits += ch; }

break and continue Statements string text = ""; for (int i = 0; i < 10; i++) { if (i % 2 == 0) continue; if (i > 8) break; text += i.ToString(); }

Caution! int index = 0; while (++index < lastIndex) { TestIndex(index); } int index = 0; while (index++ < lastIndex) { TestIndex(index); }

What About This? for (int i = 0; i < 10; i++) { } for (int i = 0; i < 10; ++i) { }

Debugging Loops

Debugging Summary  Stepping through code (over, into, out)  Setting breakpoints  Conditional breakpoints

Class Methods class DiscountCalculator { private decimal CalcDiscPercent(decimal inAmt) { return (inAmt > 250.0m) ? 0.10m: 0.0m; } public decimal CalcDiscAmount(decimal inAmt) { decimal percent = CalcDiscPercent(inAmt); return inAmt * percent; }

Passing Parameters

Parameters Summary  Pass zero or more parameters  Parameters can be optional  Optional parameters are "pre-defined" using constant values  Optional parameters can be passed by position or name  Recommendation: Use optional parameters cautiously

Parameters Summary  Parameters are usually passed by value  Parameters can be passed by reference  Reference parameters can change the value of the variable that was passed into the method

Events and Delegates

Event and Delegate Summary  A delegate connects an event to an event handler.  The delegate specifies the handler’s return type and parameters.  Event handlers can be shared with multiple controls

Exceptions and Validation

Exceptions Exception Format ExceptionArithmetic ExceptionFormat ExceptionArithmetic Exception

Format Exception string value = “ABCDEF”; int number = Convert.ToInt32(value);

Overflow Exception checked { byte value = 200; value += 200; int temp = 5000; byte check = (byte)temp; }

“Catching” an Exception try { int dividend = 20; int divisor = 0; int quotient = dividend / divisor; int next = quotient + 1; } catch { }

Responding to Exceptions  A simple message box: MessageBox.Show(message, title);  Set control focus: txtNumber.Focus();

Catching Multiple Exceptions try {} catch( FormatException e) { } catch(OverflowException e) { } catch(Exception e) { } finally { }

Throwing an Exception throw new Exception(“Really bad error!”); try { } catch(FormatException e) { throw e; }