Advanced C# Types Tom Roeder CS215 2006fa. From last time out parameters difference is that the callee is required to assign it before returning not the.

Slides:



Advertisements
Similar presentations
Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Advertisements

Object Oriented Programming with Java
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Java Review Interface, Casting, Generics, Iterator.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
C# Types Tom Roeder CS fa. Administration CMS is up let me know if you can’t see the course Assignments are posted may not be able to do some.
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Lecture 9 Concepts of Programming Languages
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
Abstract Data Types and Encapsulation Concepts
 2006 Pearson Education, Inc. All rights reserved Generics.
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
From C++ to C#. Web programming The course is on web programming using ASP.Net and C# The course is on web programming using ASP.Net and C# ASP.Net is.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
Java Implementation: Part 3 Software Construction Lecture 8.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
C#.Net Development Version 1.0. Overview Nullable Datatype Description ? HasValue Lifted Conversions null coalescing operator ?? Partial Classes Copyright.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Jon Shemitz Complicated stuff, quickly..NET 2.0. ● Generics50% & Nullable Types ● Iterators 10% ● Delegate Enhancements35% ● Partial Types5%
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
ECE122 Feb. 22, Any question on Vehicle sample code?
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
1 Chapter 11 © 1998 by Addison Wesley Longman, Inc The Concept of Abstraction - The concept of abstraction is fundamental in programming - Nearly.
1 CS Programming Languages Class 22 November 14, 2000.
1 Copyright © 1998 by Addison Wesley Longman, Inc. Chapter 10 Abstraction - The concept of abstraction is fundamental in programming - Nearly all programming.
Introduction to C# By: Abir Ghattas Michel Barakat.
Singleton Pattern. Problem Want to ensure a single instance of a class, shared by all uses throughout a program Context Need to address initialization.
1 Introduction to Object Oriented Programming Chapter 10.
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Value Types. 2 Objectives Discuss concept of value types –efficiency –memory management –value semantics –boxing –unboxing –simple types Introduce struct.
C# for C++ Programmers 1.
Java Primer 1: Types, Classes and Operators
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
Lecture 9 Concepts of Programming Languages
Compiler Design 18. Object Oriented Semantic Analysis (Symbol Tables, Type Checking) Kanat Bolazar March 30, 2010.
Conditional Statements
Chapter 14 Abstract Classes and Interfaces
Class.
Java Programming Language
Lecture 9 Concepts of Programming Languages
Presentation transcript:

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 case with ref parameters caller is not required to set an out parameter before passing it in

Constructs for Small Data enum like in C: give names to a family of values eg. Color c = Red can define enum Color { Red, Orange, Blue }; as in C, can give values to each implicit conversion to integers as needed enums are value types

Nullable Types Old software engineering problem: what is the default “unassigned” int value -1? 0? some random value? problem is that any of these may be meaningful e.g., int fd = socket(…), int t = tempInKelvin()? C# 2.0 adds nullable types given a value type, eg. int, use int? a now can be set to null

Nullable Types Now null can function as the default for all compiler sets up boxing/unboxing as needed box contains a slot to note that it is null Just like implementation with a flag done in the compiler: type-checked less tedious and error-prone Conversion between types still works as long as there already was a conversion

Partial Types Another software engineering concern how to separate generated and written code? often need to be in same class eg. from Visual Studio’s wizards C# 2.0 solution: allow multiple files public partial class A { … } each file uses partial compiler joins the class specs

Notes 2.0 keywords can be used as identifiers partial, where, yield (good, since those are useful variable names) compiler distinguishes on context in fact, can make any keyword a regular ident two ways: Unicode characters: int \u0066\u006f\u0072 = symbol: = 137 Why?

Notes static constructors add keyword static to constructor will be called when first instance is constructed useful for class-specific data eg. sequence numbers, connections to services explicit interface member instantiations expose a method only when explicitly cast to iface write interface name before method name eg. public void ICollector.Collect() { … }

Generics - Motivation Consider hashtable usage in C# just like the Java way each object has an associated HashCode hash tables use this code to place and search obj o IDictionaryEnumerator ide = h.GetEnumerator(); while(ide.MoveNext()) { String VIN = (String)ide.Key; Car car = (Car)ide.Value; Console.WriteLine(“Drive off in car {0}”, VIN); car.Drive(); }

Generics – Motivation Unfortunate that hash doesn’t know: key is string value is Car Could easily add wrong type (get exception) But: don’t want to code a new hash each time prefer general implementations Thus need a meta-variable for the type(s) like templates in C++, but well-typed

Generics Write public class Stack { … } T is the type variable will be instantiated when declared Stack intStack = new Stack (); Push some type failures to compile time goal of software engineering Can have arbitrarily many type parameters Dictionary

Constraints on Generics What if we want to write public class Stack { public T PopEmpty() { return new T(); } } Will this work? In C++, yes. What’s wrong here?

Where clauses Need a type-safe way public class Stack where T : new() { public T PopEmpty() { return new T(); } } new constraints guarantees public parameterless constructor no more parameters currently allowed workaround?

Further Constraints Suppose have interface public interface iface { public void Ping(); } Want to assume that T implements iface public class Stack where T : iface { public void PingTop() { top.Ping(); } } No need to cast compiler uses type information to decide eg. IClonable

Bare Type Constraints class StructWithClass where S: struct, T where T: U {... } Can require class/struct = reference/value type another parameter type compatible with this parameter Think of drawing subtype relations (graphs)

Open and closed types Type is open if it is an unresolved type parameter contains an unresolved type parameter Closed if not open eg. T x = new T(); Stack s; C c;

Accessibility of types Suppose C is public and A is private what is the accessibility of C ? Cannot be constructed as public must be private In general? take the intersection of all accessibility public, protected, internal, private, protected internal

Errors class A {...} class B {...} class Incompat where S: A, T where T: B {... }

Errors class StructWithClass where S: struct, T where T: U where U: A {... }

Errors interface I { void F(); } class X : I, I { void I.F() {...} void I.F() {...} }

Better iterators with Generics Implement IEnumerable then implement public IEnumerator GetEnumerator() { // eg. implementation for a Set foreach (T key in elements.keys) { yield return key; } }

Quirk Need to implement two methods: IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } Really should be generated by compiler IEnumerator inherits from IEnumerator

Notes Null coalescing operator ?? a ?? b is a if a is non-null and b otherwise internal modifier Can only be accessed in this namespace internal class C { … } Parse this F(G (7)) rule: ( ) ] > : ;,. ?

Notes Collection Pattern for a class C Contains a public GetEnumerator that returns a class/struct/interface type (call it E) E contains a public method with signature MoveNext() and return type bool E contains a public property Current that permits reading the current value type of Current is called the element type Then foreach will work

Notes Can implement more than one iterator public IEnumerable BottomToTop { get { for (int i = 0; i < count; i++) { yield return items[i]; } } } public IEnumerable TopToBottom { get { return this; } }