1 / 41

Enumerations and Attributes

Enumerations and Attributes. C# OOP Advanced. SoftUni Team. Technical Trainers. Software University. http://softuni.bg. Table of Contents. Enumerations Defining Enumerated Types Using Enumerated Types Attributes Applying Attributes to Code Elements Built-in Attributes

macgregor
Download Presentation

Enumerations and Attributes

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. Enumerations and Attributes C# OOP Advanced SoftUni Team Technical Trainers Software University http://softuni.bg

  2. Table of Contents • Enumerations • Defining Enumerated Types • Using Enumerated Types • Attributes • Applying Attributes to Code Elements • Built-in Attributes • Defining Attributes

  3. Questions sli.do#CSHarp-OOP

  4. Enumerations Sets of Constant Objects

  5. Enumerations public enumSeason { Spring, Summer, Autumn, Winter } public static void main() { Season summer = Season.Summer; // use enum… } • Object type, limited to a set of values

  6. Enumerations in switch-case Season season = Season.Summer; switch (season) { case Season.Spring: //… break; case Season.Summer: //… break; case Season.Autumn: //… break; case Season.Winter: //… break; } • You can use enum values in a switch-case statements

  7. Enum Default Value Season season = Season.Spring; if (season == Season.Spring) { Console.WriteLine((int)season); } // 0 • Underlying value of this enum is int • When we use an Season variable, we are using an int

  8. Enum Values Array seasons= Enum.GetValues(typeof(Season)); string[] names= Enum.GetNames(typeof(Season)); foreach (var season in seasons) { Console.WriteLine(season); } default toString() returns the name • GetValues()– returns an array with all constants

  9. Enum Parse Season s = (Season)Enum.Parse(typeof(Season), "Summer"); if (pet == Season.Summer) { Console.WriteLine("Let go to beach!"); } // Let go to beach! You need to cast it to enum • A stringvaluecan be convert to an equivalent enum

  10. Enum Parse (2) Produce exception if enum doesn't consist value int number = 1 Season s = (Season)Enum.Parse(typeof(Season), Number.ToString()); if (pet == Season.Summer) { Console.WriteLine("Let go to beach!"); } // Let go to beach! • A int value have to be parsed to string first and then to enum

  11. Enum Parse (3) Season season; if (Enum.TryParse("1", out season)) Console.WriteLine(season); // Summer if (Enum.TryParse("9", out season)) Console.WriteLine(season); // 9 if (Enum.TryParse("Dog", out season)) Console.WriteLine(season); // null • Safety convert to enum

  12. Problem: Weekdays Sorted by weekday, then by Notes • Create Enum Weekdaywith days from Monday through Sunday • Class WeeklyCalendar • void AddEntry(string weekday, string notes) • Iterable<WeeklyEntry> WeeklySchedule • Class WeeklyEntry(string weekday, string notes) • ToString() – "{weekday} - {notes}", ex. "Monday - sport"

  13. Solution: Weekday public enum WeekDay { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

  14. Solution: Weekday (2) public class WeeklyEntry : IComparable<WeeklyEntry> { private WeekDay weekDay; public WeeklyEntry(string weekday, string notes) { Enum.TryParse(weekday, out this.weekDay); this.Notes = notes; } public WeekDay WeekDay => this.weekDay; public string Notes { get; private set; } public override string ToString() => $"{this.WeekDay} - {this.Notes}"; //TODO: Implement CompareTo() }

  15. Solution: Weekday (3) class WeeklyCalendar { public WeeklyCalendar() { this.WeeklySchedule = new List<WeeklyEntry>(); } public List<WeeklyEntry> WeeklySchedule { get; } public void AddEntry(string weekday, string notes) { this.WeeklySchedule.Add(new WeeklyEntry(weekday, notes)); } }

  16. Enum Custom Value public enum CoffeePrice { None, Small = 50, Normal = 100, Double = 200 } • Each int value can be specified • Good practice is first element to be None

  17. Comparing Enums Season season = Season.Summer; Season season2= Season.Winter; Console.WriteLine(season.CompareTo(season2)); // -1 Comparison of ordinal values • Enumsare IComparable

  18. Problem: Coffee Machine TEN TWENTY TWENTY Small Espresso END Single coffee sold - "Small Espresso" • Class CoffeeMachine • void buyCoffee(string size, string type) • void insertCoin(string coin) • Iterable<CoffeeType> coffeesSold • Enum CoffeeType - Espresso, Latte, Irish • Enum Coin – 1, 2, 5, 10, 20, 50 (ONE, TWO, etc.) • Enum CoffeePrice - Small (50 c), Normal (75 c), Double (100 c)

  19. Solution: Coffee Machine public enum Coin { None = 0, One = 1, Two = 2, Five = 5, Ten = 10, Twenty = 20, Fifty = 50 }

  20. Solution: Coffee Machine (2) public enum CoffeeType { Espresso, Latte, Irish } public enum CoffeePrice { None, Small = 50, Normal = 100, Double = 200 }

  21. Solution: Coffee Machine (3) public class CoffeeMachine { private List<CoffeeType> coffeesSold = new List<CoffeeType>(); private int coins; public IEnumerable<CoffeeType> CoffeesSold => this.coffeesSold; public void InsertCoin(string coin) { Coin rem = (Coin)Enum.Parse(typeof(Coin), coin); this.coins += (int)rem; } //TODO: Implement BuyCoffee() (next slide) }

  22. Solution: Coffee Machine (3) public void BuyCoffee(string price, string type) { CoffeeType coffeeType = (CoffeeType)Enum.Parse(typeof(CoffeeType), type); CoffeePrice coffeePrice = (CoffeePrice)Enum.Parse(typeof(CoffeePrice), price); if (this.coins >= (int)coffeePrice) { this.coffeesSold.Add(coffeeType); this.coins = 0; } }

  23. Strategy Pattern • Encapsulates an algorithm inside a class • Making each algorithm replaceable by others • All the algorithms can work with the same data transparently • The client can work with each algorithm transparently • http://www.dofactory.com/net/strategy-design-pattern

  24. Strategy Pattern – Example public class QuickSort : SortStrategy { public void Sort(IList<object> list) { ... } } Concrete implementation Concrete implementation public class MergeSort : SortStrategy { public void Sort(IList<object> list) { ... } } public interface SortStrategy { void Sort(IList<object> list); }

  25. Strategy Pattern – Example (2) class SortedList { private IList<object> list = new List<object>(); public void Sort(SortStrategy sortStrategy) { sortStrategy.Sort(list); } // sortStrategy can be passed in constructor or like method parameter }

  26. Working with Enumerations Live Exercises in Class (Lab)

  27. Attributes Data About Data

  28. Attributes [Obsolete] public void DeprecatedMethod { Console.WriteLine("Deprecated!"); } • Data holding class • Describes parts of your code • Applied to: Classes, Fields, Methods, etc.

  29. Attributes Usage [Obsolete] public enum Coin // • Generate compiler messages or errors • Tools • Code generation tools • Documentation generation tools • Testing Frameworks • Runtime – ORM, Serialization etc.

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

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

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

  33. Custom Attributes Requirements Must inherit the System.Attribute class Their names must end with "Attribute" Possible targets must be defined via [AttributeUsage] Can define constructors with parameters Candefinepublic fields and properties

  34. Problem: Create Attribute • Create attribute Author with a string element called name, that: • Can be used over classes and methods • Allow multiple attributes of same type

  35. Solution: Create Attribute [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] class SoftUniAttribute: Attribute { public SoftUniAttribute(string name) { this.Name = name; } public string Name { get; set; } }

  36. Problem: Coding Tracker • Create a class Tracker with a method: • void PrintMethodsByAuthor() • Using simple reflection print to console authors for all methods

  37. Solution: Coding Tracker var type = typeof(StartUp); var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static); foreach (var mInfo in methods) { if (mInfo.CustomAttributes .Any(n => n.AttributeType == typeof(SoftUniAttribute))) { var attrs = methodInfo.GetCustomAttributes(false); foreach (SoftUniAttribute attr in attrs) { Console.WriteLine($"{mInfo.Name} is written by {attr.Name}"); } } }

  38. Summary • Enumerations define a fixed set of constants • E.g. RGB colors • Are much like classes • Cannot be inherited • Attributes allow adding metadata in classes / types / etc. • Built-in attributes • Custom attributes • Can be accessed at runtime

  39. Enumerations and Annotations https://softuni.bg/courses/advanced-csharp

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

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

More Related