1 / 33

Notes on C# and object oriented programming for CSE 3902

Notes on C# and object oriented programming for CSE 3902. Outline. Key points on C# Demo of development environment Key points on object oriented software and component based software More specific information on C# syntax and terminology. Why C#?. Compared to other languages

kaspar
Télécharger la présentation

Notes on C# and object oriented programming for CSE 3902

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Notes on C# and object oriented programming for CSE 3902

  2. Outline • Key points on C# • Demo of development environment • Key points on object oriented software and component based software • More specific information on C# syntax and terminology

  3. Why C#? • Compared to other languages • Focus on object oriented programming • .NET framework • Large library of features and objects • Portability and integration with software written in other languages • More discussion here • Other reasons • Game engines support C# -> XNA, Monogame, Unity • Useful in other CSE courses (3541 Game and Animation Techniques and 5912 Game Capstone) • Visual Studio is a single point of access for software development, source code control, project management, and code reviews and is Microsoft software -> use Microsoft developed language

  4. Namespaces Classes Fields Properties Methods Attributes Events Interfaces (contracts) Methods Properties Events Control Statements if, else, while, for, switch foreach Additional Features Operation Overloading Structs Enums OO Features Type Unification Inheritance Polymorphism Language

  5. Some syntax to know about C# • No pointers. Use the dot “.” to access both namespaces and fields/methods. • Automatic memory management – garbage collection • All fields are initialized by the CLR (zero for value types, null for reference types) • Structs are value type, classes are reference type • Switch statements • Does not “fall-thru” (unless empty) • Can take bool’s , enum’s, integer types, and strings • Expressions must be useful (no a==b;) • Conditionals must evaluate to a Boolean

  6. VS 2012 and XNA demo

  7. Why Object-Oriented Programming? • Code Reuse • Objects made for one program are usable in another. • Inheritance - objects can reuse parts of other objects without modifying the original • Polymorphism - an operation may exhibit different behaviors in different instances (i.e. it can take on multiple forms) • Encapsulation • All data and functionality for an object are included inside its implementation • For a well designed object, the client/user of an object does not need to know its implementation details. • The implementer of the object controls what functionality of the object is available to clients • Design Benefits • Creation of objects encourages planning as objects must be implemented before being used • Generally speaking: more planning = less flaws • Software Maintenance • Object implementation is not coupled to the application, thus making changes to either is easier • Additional discussion can be found here

  8. An alternative – entity component system • A component encapsulates a specific set of functions or data • Entities are objects that may have any number of attached components • Example – Unity game engine • Almost everything is a GameObject • Components can be attached to GameObjects • Ex: Collider, RigidBody, Scripts, etc. • Every component is updated by a corresponding system or manager class

  9. Object-oriented vs. Component based • OOP • Focus on readability • Objects are an abstraction to be used by client programmers, and should follow a mental model of the actual or imagined object it represents • Objects are “nouns” that have fields “adjectives” and methods “verbs” • Components • Focus on reusability • Software should be constructed by gluing together prefabricated components like in electrical engineering • Functionality is attached to an object instead of inside its implementation

  10. Interfaces

  11. Interfaces • An interface defines a contract • An interface is a type • Contain definitions for methods, properties, indexers, and/or events • Any class or struct implementing an interface must support all parts of the contract • Interfaces provide no implementation • When a class or struct implements an interface it must provide the implementations

  12. Interfaces • Explicit interface • Requires/ensures clauses or Pre/postconditions • Functionality is explicitly defined • Implicit interface • Only method signatures are specified • Ex: Bird interface defines void Fly() Duck class implements void Fly { position.y += 5; } Penguin class implements void Fly { // no-op }

  13. Interfaces Example public interface IDelete { void Delete(); } public class TextBox : IDelete { public void Delete() { ... } } public class Car : IDelete { public void Delete() { ... } } TextBoxtb = new TextBox(); tb.Delete(); Car c = new Car(); IDeleteiDel= c; iDel.Delete();

  14. Object and interface design • Keep it simple! • The Magical Number Seven, Plus or Minus Two • The average person can hold 7 ± 2 objects in memory at a time • Experts recall more by “chunking” – combining multiple objects into one • Think You're Multitasking? Think Again • The average person is bad at multi-tasking, so focus on what you’re doing if you want it done well • Only provide the minimum amount of functionality required • You can always add functionality later, but beware functionality bloat

  15. Class internals

  16. this • The this keyword is a predefined variable available in non-static function members • Used to access data and function members unambiguously name is a parameter and a field. public class Person { private string name; public Person(string name) { this.name = name; } public void Introduce(Person p) { if (p != this) Console.WriteLine(“Hi, I’m “ + name); } }

  17. base • The base keyword can be used to access class members that are hidden by similarly named members of the current class public class Shape { private int x, y; public override string ToString() { return "x=" + x + ",y=" + y; } } internal class Circle : Shape { private int r; public override string ToString() { return base.ToString() + ",r=" + r; } }

  18. Constants • A constant is a data member that is evaluated at compile-time and is implicitly static (per type) • e.g. Math.PI public class MyClass { public const string version = “1.0.0”; public const string s1 = “abc” + “def”; public const int i3 = 1 + 2; public const double PI_I3 = i3 * Math.PI; public const double s = Math.Sin(Math.PI); //ERROR ... }

  19. Fields • A field or member variable holds data for a class or struct • Can hold: • A built-in value type • A class instance (a reference) • A struct instance (actual data) • An array of class or struct instances (an array is actually a reference) • An event

  20. Properties • A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods. • Properties encapsulate a getting and setting a field • Useful for changing the internal type for a field • Useful for adding code or breakpoints when getting/setting a field

  21. Properties – examples • type PropertyName{ get; set; } • Examples int Score { get; set; } double Time { get; private set; } string Name { get; } • Code examples • person.cs (see course calendar for link) • abstractshape.cs (see course calendar for link) • http://www.dotnetperls.com/property

  22. Methods (a.k.a. functions) • All code executes in a method • Constructors, destructors and operators are special types of methods • Properties and indexers are implemented with get/set methods • Methods have argument lists • Methods contain statements • Methods can return a value

  23. Modifiers • Public • Accessible anywhere • Protected • Accessible within its class and by derived class instances • Private • Accessible only within the body of the class • (Or anywhere if you use reflection) • Static • Belongs to the type • Instance • Belongs to the instance

  24. Static field example public class Variable { public static inti = 5; public void test() { i=i+5; Console.WriteLine(i); } } public class Exercise { static void Main() { Variable var = new Variable(); var.test(); Variable var1 = new Variable(); var1.test(); Console.ReadKey(); } } Output is: 10 15

  25. Classes vs. Structs

  26. Classes vs. Structs • Both are user-defined types • Both can implement multiple interfaces • Both can contain • Data • Fields, constants, events, arrays • Functions • Methods, properties, indexers, operators, constructors • Type definitions • Classes, structs, enums, interfaces, delegates

  27. Classes vs. structs

  28. Class definition syntax public class Car : Vehicle { public enum Make { GM, Honda, BMW } private Make make; private string vid; private Point location; Car(Make make, string vid, Point loc) { this.make = make; this.vid = vid; this.location = loc; } public void Drive() { Console.WriteLine(“vroom”); } } Car c = new Car(Car.Make.BMW, “JF3559QT98”, new Point(3,7)); c.Drive();

  29. Struct definition syntax public struct Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point p = new Point(2,5); p.X += 100; int px = p.X; // px = 102

  30. Conversion

  31. Conversion operators • Can also specify user-defined explicit and implicit conversions internal class Note { private int value; // Convert to hertz – no loss of precision public static implicit operator double(Note x) { return ...; } // Convert to nearest note public static explicit operator Note(double x) { return ...; } } Note n = (Note)442.578; double d = n;

  32. The is Operator • The is operator is used to dynamically test if the run-time type of an object is compatible with a given type private static void DoSomething(object o) { if (o is Car) ((Car)o).Drive(); }

  33. The as Operator • The as operator tries to convert a variable to a specified type; if no such conversion is possible the result is null • More efficient than using is operator • Can test and convert in one operation private static void DoSomething(object o) { Car c = o as Car; if (c != null) c.Drive(); }

More Related