C# for C++ Programmers 1.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

INHERITANCE BASICS Reusability is achieved by INHERITANCE
Road Map Introduction to object oriented programming. Classes
Slides prepared by Rose Williams, Binghamton University Chapter 13 Interfaces and Inner Classes.
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++
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Lecture 9 Concepts of Programming Languages
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Distributed Systems (236351) Tutorial 1 - Getting Started with Visual Studio C#.NET.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Introduction to Building Windows 8.1 & Windows Phone Applications.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Objects and Classes.
Introduction to Object-Oriented Programming Lesson 2.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 9 Introduction of Object Oriented Programming.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Chapter 2 Objects and Classes
Topic: Classes and Objects
Creating and Using Objects, Exceptions, Strings
Creating Your Own Classes
Abstract Data Types and Encapsulation Concepts
Object-Oriented Programming: Classes and Objects
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
7. Inheritance and Polymorphism
2.7 Inheritance Types of inheritance
Final and Abstract Classes
Methods Attributes Method Modifiers ‘static’
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
University of Central Florida COP 3330 Object Oriented Programming
Structs.
Object-Oriented Programming: Classes and Objects
C# In many ways, C# looks similar to Java
Lecture 9 Concepts of Programming Languages
Pass by Reference, const, readonly, struct
Introduction to Classes
Interface.
Abstract Data Types and Encapsulation Concepts
Java Programming Language
Conditional Statements
Interfaces.
Chapter 9 Objects and Classes
Classes and Objects.
Java Inheritance.
Tonga Institute of Higher Education
Fundaments of Game Design
How to organize and document your classes
Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
Introduction to Classes and Objects
Class.
Final and Abstract Classes
Corresponds with Chapter 5
Lecture 9 Concepts of Programming Languages
Chengyu Sun California State University, Los Angeles
Presentation transcript:

C# for C++ Programmers 1

C#: the basics Lots of similarities with C++ Object Oriented Classes, structs & enums Familiar basic types: int, double, bool, … Familiar keywords: for, while, if, else, … Similar syntax: curly braces { }, dot notation, … Exceptions: try and catch

C#: the basics More closely resembles Java Everything lives in a class/struct (no globals) No pointers! (so no ->, * or & notation) Garbage collection: no delete No header files No multiple inheritance Interfaces Static members access with . (not ::)

C# Features Properties Interfaces The foreach keyword The readonly keyword Parameter modifiers: ref and out Delegates and events Instead of callbacks Generics Instead of templates

Properties Class members, alongside methods and fields field is what C# calls a member variable Properties “look like fields, behave like methods” By convention, names are in UpperCamelCase

Properties: simple example class Thing { // Private field private String _name; // Public property public String Name get return _name; } set // “value” is an automatic // variable inside the setter _name = value; class Program { static void Main (string[] args) Thing t = new Thing (); // Use the setter t.Name = “Brutus” // Use the getter Console.WriteLine (t.Name); }

Properties: even simpler example class Thing { // Private field (the “backing field”) private String _name; // Public property public String Name get return _name; } set name = value; class Thing { // If all you want is a simple getter/ // setter pair, no need for a backing // field public String Name { get; set; } }

Properties: advanced getter/setter class Thing { // Private field private String _name; private static int refCount = 0; // Public property public String Name get return _name.ToUpper (); } set _name = value; refCounter++; Can hide implementation detail inside a property Hence “looks like a field, behaves like a method”

Properties: access modifiers class Thing { // Private field private String _name; // Public property public String Name get return _name; } private set _name = value; Now only the class itself can modify the value Any object can get the value

Properties: getter only class Thing { // Public property public int CurrentHour get return DateTime.Now.Hour; } In this case it doesn’t make sense to offer a setter Can also implement a setter but no getter Notice that Now and Hour are both properties too (of DateTime) – and Now is static

Interfaces Very similar to Interfaces in Java Like a class, but all its members are implicitly abstract C++ - all methods pure virtual (= 0) i.e. does not provide any method implementations, only method signatures A class can only inherit from a single base class, but may implement multiple interfaces

Limitations of Interfaces Interfaces cannot have data members They cannot define constructors or destructors Differences and similarities between an Interface and an abstract class Differences Interfaces cannot contain any implementation Interfaces cannot declare non-public members Interfaces cannot extend non-interfaces Similarities Neither can be instantiated

Syntax for declaring an Interface interface InterfaceName { refType methodName1 (param-list); // … } They are essentially abstract methods Methods declared in an interface are implicitly public; no explicit access specifier is allowed

Syntax for implementing an Interface class ClassName : InterfaceName { // Class body } When a class is implementing an interface it has to implement the entire interface A class can implement more than one interface separated by a comma A class can also inherit from a base class in combination with an interface; the name of the base class will be listed first

Simple Interface example using System; class Demo : Iabc { public static void Main (string[] args) Console.WriteLine (“Hello Interfaces”); Demo refDemo = new Demo (); refDemo.xyz (); } public void xyz () Console.WriteLine (“In Demo :: xyz”); interface Iabc void xyz (); Result: > Hello Interfaces > In Demo :: xyz

foreach Simplified for loop syntax int[] myInts = new int[] { 1, 2, 3, 4, 5 }; foreach (int i in myInts) { Console.WriteLine(i); } Works with built-in arrays, collection classes and any class implementing IEnumerable interface

readonly For values that can only be assigned during construction class Thing { private readonly string name; private readonly int age = 42; // OK; public Thing () name = “Brutus”; // Also OK } public void SomeMethod () name = “Buckeye”; // Error

readonly & const C# also has the const keyword As in C++, used for constant values known at compile time Not identical to C++ const though Not used for method parameters Not used for method signatures

Parameter modifiers: ref No (explicit) pointers or references in C# In effect, all parameters are passed by reference But not quite static void Main (string[] args) { String message = “Brutus”; MakeBuckeye(message); Console.WriteLine(message); } static void MakeBuckeye (string s) s += “Buckeye”; Result: > Brutus

Parameter modifiers: ref Although parameter passing is efficient as “by reference”, effect is more like “by const reference” The ref keyword fixes this static void Main (string[] args) { String message = “Brutus”; MakeBuckeye(ref message); Console.WriteLine(message); } static void MakeBuckeye (ref string s) s += “ Buckeye”; Result: > Brutus Buckeye

Parameter modifiers: out Like ref but must be assigned in the method static void Main (string[] args) { DateTime now; if (isAfternoon(out now)) Console.WriteLine(“Good afternoon, it is now “ + now.TimeOfDay.ToString ()); } else Console.WriteLine(“Please come back this afternoon.”); static bool isAfternoon (out DateTime currentTime) currentTime = DateTime.Now; return currentTime.Hour >= 12;

Delegates Delegates are how C# defines a dynamic interface between two methods Same goal as function pointers in C Delegates are type-safe Consists of two parts: a delegate type and a delegate instance

Delegates A delegate type looks like an (abstract) method declaration, preceded with the delegate keyword A delegate instance creates an instance of this type, supplying it with the name of a real method to attach to

Delegates Result: > 10 // Delegate type (looks like an abstract method) delegate int Transform(int number); static int DoubleIt (int number) { return number * 2; } static void Main (string[] args) // Create a delegate instance Transform transform; // Attach it to a real method Transform = DoubleIt; // And now call it (via the delegate) int result = transform(5) Console.WriteLine(result.ToString()); Result: > 10

Multicast delegates A delegate instance can have more than one real method attached to it Transform transform; Transform += DoubleIt; Transform += HalveIt; // etc. Now when we call transform(), all methods are called Called in the order in which they were added

Multicast delegates Methods can also be removed from a multicast delegate Transform -= DoubleIt;

Events Events are just a special, restricted form of delegate Core part of C# UI event handling Controls have standard set of events you can attach handlers to myButton.Click += OnButtonClicked;

Advanced C# and .NET Generics Assemblies Look and behave pretty much like C++ templates Assemblies Basic unit of deployment in .NET Typically a single .EXE or .DLL Extra access modifier internal (in addition to public, protected, private) gives access to other classes within the same assembly

?

References Whitaker, Mark. “C# for C++ Programmers” MSDN. “C for C++ Developers” Ikram, Aisha. “Quick C#”