410 likes | 436 Views
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
E N D
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 • Defining Attributes
Questions sli.do#CSHarp-OOP
Enumerations Sets of Constant Objects
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
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
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
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
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
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
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
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"
Solution: Weekday public enum WeekDay { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }
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() }
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)); } }
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
Comparing Enums Season season = Season.Summer; Season season2= Season.Winter; Console.WriteLine(season.CompareTo(season2)); // -1 Comparison of ordinal values • Enumsare IComparable
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)
Solution: Coffee Machine public enum Coin { None = 0, One = 1, Two = 2, Five = 5, Ten = 10, Twenty = 20, Fifty = 50 }
Solution: Coffee Machine (2) public enum CoffeeType { Espresso, Latte, Irish } public enum CoffeePrice { None, Small = 50, Normal = 100, Double = 200 }
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) }
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; } }
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
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); }
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 }
Working with Enumerations Live Exercises in Class (Lab)
Attributes Data About Data
Attributes [Obsolete] public void DeprecatedMethod { Console.WriteLine("Deprecated!"); } • Data holding class • Describes parts of your code • Applied to: Classes, Fields, Methods, etc.
Attributes Usage [Obsolete] public enum Coin // • Generate compiler messages or errors • Tools • Code generation tools • Documentation generation tools • Testing Frameworks • Runtime – ORM, Serialization etc.
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
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
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
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
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
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; } }
Problem: Coding Tracker • Create a class Tracker with a method: • void PrintMethodsByAuthor() • Using simple reflection print to console authors for all methods
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}"); } } }
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
Enumerations and Annotations https://softuni.bg/courses/advanced-csharp
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
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