Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University

Slides:



Advertisements
Similar presentations
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Advertisements

Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Consuming REST Services from C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Database APIs and Wrappers
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
Processing Redis with.NET How to Operate with Redis Databases SoftUni Team Technical Trainers Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Arrays, Lists, Stacks, Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Jekyll Static Site Generator Template-Based Site Generation Svetlin Nakov Technical Trainer Software University
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes SoftUni Team Technical Trainers Software University
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Operators and Expressions
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
Static Members, Structures, Enumerations, Generic Classes, Namespaces Telerik Software Academy Object-Oriented Programming.
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
C# OOP Advanced Course Introduction SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Static Members and Namespaces
Defining Classes – Part II
Presentation transcript:

Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University

Table of Contents 1.Enumerations 2.Structures 3.Generic Classes 4.Attributes 2

Enumerations Defining and Using Enumerated Types

4  Enumerations are types that hold a value from a fixed set of named constants, declared by the enum keyword in C# Enumerations in C# public enum DayOfWeek { Mon, Tue, Wed, Thu, Fri, Sat, Sun Mon, Tue, Wed, Thu, Fri, Sat, Sun} class EnumExample { static void Main() static void Main() { DayOfWeek day = DayOfWeek.Wed; DayOfWeek day = DayOfWeek.Wed; Console.WriteLine(day); // Wed Console.WriteLine(day); // Wed }}

5 Enumerations – Example public enum CoffeeSize { Small = 100, Normal = 150, Double = 300 Small = 100, Normal = 150, Double = 300} public class Coffee { public CoffeeSize size; public CoffeeSize size; public Coffee(CoffeeSize size) public Coffee(CoffeeSize size) { this.size = size; this.size = size; } public CoffeeSize Size public CoffeeSize Size { get { return size; } get { return size; } } } (the example continues)

6 Enumerations – Example (2) public class CoffeeMachine { static void Main() static void Main() { Coffee normalCoffee = new Coffee(CoffeeSize.Normal); Coffee normalCoffee = new Coffee(CoffeeSize.Normal); Coffee doubleCoffee = new Coffee(CoffeeSize.Double); Coffee doubleCoffee = new Coffee(CoffeeSize.Double); Console.WriteLine("The {0} coffee is {1} ml.", Console.WriteLine("The {0} coffee is {1} ml.", normalCoffee.Size, (int)normalCoffee.Size); normalCoffee.Size, (int)normalCoffee.Size); // The Normal coffee is 150 ml. // The Normal coffee is 150 ml. Console.WriteLine("The {0} coffee is {1} ml.", Console.WriteLine("The {0} coffee is {1} ml.", doubleCoffee.Size, (int)doubleCoffee.Size); doubleCoffee.Size, (int)doubleCoffee.Size); // The Double coffee is 300 ml. // The Double coffee is 300 ml.}}

Enumerations Live Demo

C# Structures

9  What is a structure in C#?  A value data type (behaves like a primitive type)  Examples of structures: int, double, DateTime  Classes are reference types  Declared by the keyword struct  Structures have fields, properties, constructors, methods, etc. (just like classes)  Always have a parameterless constructor  It cannot be removed  Mostly used to store data (a bunch of fields) C# Structures

10 struct Point { public int X { get; set; } public int X { get; set; } public int Y { get; set; } public int Y { get; set; }} struct Color { public byte RedValue { get; set; } public byte RedValue { get; set; } public byte GreenValue { get; set; } public byte GreenValue { get; set; } public byte BlueValue { get; set; } public byte BlueValue { get; set; }} enum Edges { Straight, Rounded } (example continues) C# Structures – Example

11 struct Square { public Point Location { get; set; } public Point Location { get; set; } public int Size { get; set; } public int Size { get; set; } public Color SurfaceColor { get; set; } public Color SurfaceColor { get; set; } public Color BorderColor { get; set; } public Color BorderColor { get; set; } public Edges Edges { get; set; } public Edges Edges { get; set; } public Square(Point location, int size, public Square(Point location, int size, Color surfaceColor, Color borderColor, Color surfaceColor, Color borderColor, Edges edges) : this() Edges edges) : this() { this.Location = location; this.Location = location; this.Size = size; this.Size = size; this.SurfaceColor = surfaceColor; this.SurfaceColor = surfaceColor; this.BorderColor = borderColor; this.BorderColor = borderColor; this.Edges = edges; this.Edges = edges; }} C# Structures – Example (2)

C# Structures Live Demo

Generic Classes Parameterizing Classes

14  Generics allow defining parameterized classes that process data of unknown (generic) type  The class is instantiated (specialized) with different particular types  Example: List  List / List / List / List  Generics are known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java What are Generics?

15 Generic Class – Example public class GenericList public class GenericList { public void Add(T element) { … } public void Add(T element) { … }} class GenericListExample { static void Main() static void Main() { // Declare a list of type int // Declare a list of type int GenericList intList = GenericList intList = new GenericList (); new GenericList (); // Declare a list of type string // Declare a list of type string GenericList stringList = GenericList stringList = new GenericList (); new GenericList (); }} T is an unknown type, parameter of the class T can be used in any method in the class T can be replaced with int during the instantiation

Generic Classes Live Demo

17  Methods can also be generic  Can take generic input and return generic output Generic Methods public static T[] CreateArray (T value, int count) { T[] arr = new T[count]; T[] arr = new T[count]; for (int i=0; i<count; i++) arr[i] = value; for (int i=0; i<count; i++) arr[i] = value;} static void Main() { string[] strings = CreateArray("hello", 5); string[] strings = CreateArray("hello", 5); Console.WriteLine(String.Join(", ", strings)); Console.WriteLine(String.Join(", ", strings));}

Generic Method – Example public static T Min (T first, T second) where T : IComparable where T : IComparable { if (first.CompareTo(second) <= 0) if (first.CompareTo(second) <= 0) return first; return first; else else return second; return second;} static void Main() { int i = 5; int i = 5; int j = 7; int j = 7; int min = Min (i, j); int min = Min (i, j);} 18

Generic Methods Live Demo

Attributes Applying Attributes to Code ElementsApplying Attributes to Code Elements

21 .NET attributes are:  Declarative tags for attaching descriptive information in the declarations in the code  Saved in the assembly at compile time  Objects derived from  Objects derived from System.Attribute  Can be accessed at runtime (through reflection) and manipulated by many tools  Developers can define custom attributes What are Attributes?What are Attributes?

22  Attribute's name is surrounded by square brackets: []  Placed before their target declaration attribute indicates that the enum type can be treated like a set of bit flags  [Flags] attribute indicates that the enum type can be treated like a set of bit flags Applying Attributes – ExampleApplying Attributes – Example [Flags] // System.FlagsAttribute public enum FileAccess { Read = 1, Read = 1, Write = 2, Write = 2, ReadWrite = Read | Write ReadWrite = Read | Write}

23  Attributes can accept parameters for their constructors and public properties  The attribute refers to:  The [DllImport] attribute refers to:  System.Runtime.InteropServices.DllImportAttribute  "" is passed to the constructor  " user32.dll " is passed to the constructor  "" value is assigned to  " MessageBox " value is assigned to EntryPoint Attributes with Parameters (2)Attributes with Parameters (2) [DllImport("user32.dll", EntryPoint="MessageBox")] public static extern int ShowMessageBox(int hWnd, string text, string caption, int type); string text, string caption, int type);… ShowMessageBox(0, "Some text", "Some caption", 0);

24  Attributes can specify its target declaration:  See the Properties/AssemblyInfo.cs file Set a Target to an AttributeSet a Target to an Attribute // target "assembly" [assembly: AssemblyTitle("Attributes Demo")] [assembly: AssemblyCompany("DemoSoft")] [assembly: AssemblyProduct("Enterprise Demo Suite")] [assembly: AssemblyVersion(" ")] [Serializable] // [type: Serializable] class TestClass { [NonSerialized] // [field: NonSerialized] [NonSerialized] // [field: NonSerialized] private int status; private int status;}

Using Attributes Live Demo

26 .NET developers can define their own custom attributes  Must inherit from class  Must inherit from System.Attribute class  Their names must end with ""  Their names must end with " Attribute "  Possible targets must be defined via  Possible targets must be defined via [AttributeUsage]  Can define constructors with parameters  Can define public fields and properties Custom AttributesCustom Attributes

27 Custom Attributes – ExampleCustom Attributes – Example [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)] AllowMultiple = true)] public class AuthorAttribute : System.Attribute { public string Name { get; private set; } public string Name { get; private set; } public AuthorAttribute(string name) public AuthorAttribute(string name) { this.Name = name; this.Name = name; }} // Example continues // Example continues

28 Custom Attributes Example (2)Custom Attributes Example (2) [Author("Svetlin Nakov")] [Author("Bay Ivan")] class CustomAttributesDemo { static void Main(string[] args) static void Main(string[] args) { Type type = typeof(CustomAttributesDemo); Type type = typeof(CustomAttributesDemo); object[] allAttributes = type.GetCustomAttributes(false); object[] allAttributes = type.GetCustomAttributes(false); foreach (AuthorAttribute attr in allAttributes) foreach (AuthorAttribute attr in allAttributes) { Console.WriteLine( Console.WriteLine( "This class is written by {0}. ", attr.Name); "This class is written by {0}. ", attr.Name); } }}

Defining, Applying and Retrieving Custom Attributes Live Demo

30  Enumerations define a fixed set of constants  E.g. the days of the week  Structures are "value-type" classes  Useful for storing data by value  Generics are parameterized classes  Template classes for processing data of unknown (generic) type  Generic methods can accept generic parameter types  Attributes allow adding metadata in classes / types / etc. Summary

? ? ? ? ? ? ? ? ? Other Types in OOP

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 32  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA

SoftUni Diamond Partners

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg