Reflection, Conversions, and Exceptions Tom Roeder CS215 2006fa.

Slides:



Advertisements
Similar presentations
Inheritance Lakshmish Ramaswamy. Example A Rectangle class with area method A Circle class with area method Array containing references to circles & rectangles.
Advertisements

CS 3260 Dennis A. Fairclough Version 1.0
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
C# Structs, operator overloading & attributes. Structs ~ Structures Structs are similar to classes: they represent data structures with data and functions.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Type Type system for a programming language = –set of types AND – rules that specify how a typed program is allowed to behave Why? –to generate better.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
OOP Languages: Java vs C++
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 12: Adding Functionality to Your Classes.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Names Variables Type Checking Strong Typing Type Compatibility 1.
Java Implementation: Part 3 Software Construction Lecture 8.
2000 Jordan Anastasiade. All rights reserved. 1 Class In this lesson you will be learning about: Class. Inheritance. Polymorphism. Nested and.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Inheritance in the Java programming language J. W. Rider.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
Introduction to Exception Handling and Defensive Programming.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
CSE 425: Data Types I Data and Data Types Data may be more abstract than their representation –E.g., integer (unbounded) vs. 64-bit int (bounded) A language.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Inter-Type Declarations in AspectJ Awais Rashid Steffen Zschaler © Awais Rashid, Steffen Zschaler 2009.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Attributes C#.Net Software Development Version 1.0.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Operators and Cast. Operators Operator Shortcuts.
Inheritance and Polymorphism
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Overloading and Constructors
Extending Classes.
Java Programming Language
Abstract Classes AKEEL AHMED.
Binding 10: Binding Programming C# © 2003 DevelopMentor, Inc.
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Presentation transcript:

Reflection, Conversions, and Exceptions Tom Roeder CS fa

Remaining Constructs We’ve covered most of the core language At least as it differs from Java Need to see Reflection Exceptions Overloading/Operators Explicit and implicit casts and conversions

Reflection The ability to refer to the type system in code eg. Type t = Type.GetType(“int”); bool b = t.IsSubclassOf(typeof(object)); construct types from strings have classes that represent types Can explicitly compare types and determine subclassing (and other) relationships Useful for many applications

Reflection – Example We want to get a methods dynamically: C c = new C(); Type t = c.GetType(); for(int i = 0; i < 10; i++) { MethodInfo m = t.GetMethod(“m” + i); m.Invoke(c, null); } Type contains information about the type all nested types all methods, members, properties, etc whether or not it is an array

Reflection – is How do we get/check type information? use is operator: if (c is Guid) { … } returns true if it is this class If it is a subclass, is returns true reflects dynamic type information if compiler can decide statically, it will warn eg. int i = 0; if (i is object) { … } else { … } like instanceof in Java easy to abuse: can avoid proper inheritance

Reflection - as Instead of a cast, use as keyword returns a variable of the right type or null if not possible (no conversion exists) can only use for reference/interface types but can often convert to value types Better than trying to cast and throwing can be misused all the same may still need to cast if using a value type

Reflection – Attributes Assemblies contain metadata can be defined by programmer at compilation any class derived from System.Attribute naming convention _Attribute can be dropped and still understood using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface)] public class SimpleAttribute: Attribute {...}

Reflection – Attributes [Simple] class Class1 {...} [Simple] interface Interface1 {...} Multi-use or single-use attributes depends on AllowMultiple Positional and named parameters constructors define positional parameters non-static public RW fields define named

Reflection – Attributes Parameters limited in type numeric, string, and enum types object and System.Type single dimensional arrays of the above Uses authorship serializability help URLs any declarative information

Attribute Example Application Abstraction (see Singularity)Singularity add attributes that describe the application what resources used in OS what other applications it connects to use this information to build some components eg. access code for hardware resources add security information what does this application expect from extensions Used, eg for Device Drivers in Singularity

Attribute Example [DriverCategory] [Signature("/pci/03/00/5333/8811")] class S3TrioConfig: DriverCategoryDeclaration { // Hardware resources from PCI config [IoMemoryRange(0, Default = 0xf , Length = 0x400000)] internal readonly IoMemoryRange frameBuffer; // Fixed hardware resources [IoFixedMemoryRange(Base = 0xb8000, Length = 0x8000)] internal readonly IoMemoryRange textBuffer;

Reflection – Attributes Conditional in System.Diagnostics takes a string representing a symbol calls to method are included only if the symbol is defined at the method call point Obsolete can return compiler errors or warnings useful for long-standing code

Reflection - Attributes PInvoke can import functions from native API [DllImport(“kernel”)] NtCreateFile(…) no guarantees about called code but allows direct access to OS and others We will discuss this more when we discuss unsafe mode

Reflection – Code Generation Can dynamically instantiate assemblies Reflection allows generation of MSIL eg. System.Reflection.Emit.MethodRental allows the replacement of a body with another can add before/after clauses Could write a program that generates another this is not good style but the power is occasionally useful

Conversions Implicit never fails to a “larger” type eg. int to long Explicit may fail to a “smaller” type eg. long to int User-defined conversions should be similar

Conversions Don’t make an implicit conversion that fails! or one across very different domains Implicit example: boxing conversion to an implemented interface User-defined conversions can define a conversion “operator” if not already defined and operates on our class

Conversions C# will only take one jump to convert eg. if have conversion S to X and X to T, will not convert S to T eg. public static implicit operator Hashtable(Example e) { Hashtable h = new Hashtable(); h[e.a.X] = e.a.X; return h; }

Operators Defines the meaning of an operator eg. +, -, *, /, % static method operates on two instances and returns a third unlike C++ where one instance is implicit one of the classes must be the defining class Can’t be part of an interface Can’t be overridden

Operator Examples public static C operator +(C first, C second) { C temp = new C(); temp.val = first.val + second.val; return temp; }

Operator Examples Suppose have class C that has a conversion to double and back. Is the following valid? C c1 = new C(); C c2 = new C(); C c3 = (C)((double)c1 + (double)c2); does it worry you? it should: why should + actually work like this? depends strongly on the conversion used what is the right way to do this?

Exceptions Inherit from System.Exception Control structure same as Java try-catch-finally can implement own exceptions Dynamic exceptions can occur at runtime eg. NullReference, OutOfBounds necessary to catch them

Exceptions Interesting cases: InnerExceptions any number of nested exceptions common interface to nesting Initializer catching exceptions implicitly then throws System.TypeInitializationException Exceptions in destructor try to execute base class otherwise discard exception

Checked and Unchecked Two contexts for evaluating arithmetic unchecked default context overflows do not throw exceptions can use unchecked operator to make explicit checked overflows throw System.OverflowException use checked operator