14
Structures and Enumerations 1 C# 30 C# 3.0 C# 3.0 Chapter 9 – Structures and Enumerations Enumerations © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel Introduction Structures and Enumerations 2 C# 30 Introduction Classes are good but we need more Classes are good, but we need more types! Structures a limited, yet more efficient version of classes Enumerations These types are value-type user defined types types Delegates and interfaces (two new reference type types) will be discussed later will be discussed later © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Chapter 9 - Structures and Enumerations

Embed Size (px)

DESCRIPTION

k

Citation preview

  • Structures and Enumerations 1C# 30

    C# 3.0C# 3.0

    Chapter 9 Structures and EnumerationsEnumerations

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    IntroductionStructures and Enumerations 2C# 30

    Introduction Classes are good but we need more Classes are good, but we need more

    types! Structures a limited, yet more efficient version of

    classes Enumerations

    These types are value-type user defined typestypes Delegates and interfaces (two new reference type types)

    will be discussed laterwill be discussed later

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Structures and Enumerations 3C# 30

    SStructures

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    C# StructuresStructures and Enumerations 4C# 30

    C# StructuresClasses might sometimes be too hea Classes might sometimes be too heavy Reference type variables and their manipulation

    involves a lot of overhead

    Structures (defined using the structkeyword) are value-type user defined typestypes They are derived from System.ValueType Are allocated and directly manipulated on the stack

    (unless boxing is required)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • A Structure Example: PointStructures and Enumerations 5C# 30

    A Structure Example: Pointstruct Point{{

    publicPoint(int x,int y){_x=x;y=y;_y y;

    }publicint X{

    get{return x;}get{return_x;}set{_x=value;}

    }bli i t Y{publicint Y{get{return_y;}set{_y=value;}

    }publicoverridestringToString(){

    return"("+ x+","+ y+")";( _ , _y ) ;}privateint _x;privateint y;

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    privateint _y;}

    A Structure Example: PointStructures and Enumerations 6C# 30

    A Structure Example: Point

    Structures can declare fields, methods, propertiesproperties

    Structures can define constructors and can override virtual methods derived fromcan override virtual methods derived from System.ValueType

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Structure LimitationsStructures and Enumerations 7C# 30

    Structure Limitations Cannot be part of an inheritance tree: Cannot be part of an inheritance tree:

    They cannot inherit from other classes They are implicitly sealed Virtual methods and protected members are irrelevant

    f t tfor structures Cannot have a null value

    Only references can be pointing to null

    Cannot have a parameterless constructor Cannot have a parameterless constructor For performance reasons, it is not always called

    Cannot have a finalizer Value types are not garbage collected (unless boxed)

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    yp g g ( )

    Design GuidelinesStructures and Enumerations 8C# 30

    Design GuidelinesStr ct res sho ld be sed for light eight Structures should be used for light-weight objects with value semanticsj Point, Complex number, the Systems decimal and DateTime types, etc.ate e types, etc

    Users expect them to behave as primitive value-typesvalue-types Value semantics for equality, assignment, comparison No significant side effects

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Structure Usage ExampleStructures and Enumerations 9C# 30

    Structure Usage ExamplestaticvoidMain(){() {

    Pointp=newPoint(0,0);Console.WriteLine(p);p.X =5;p.X 5;p.Y =10;Console.WriteLine(p);int i =p X;int i =p.X;i =p.Y;

    }

    Structure instances must be created using the new operatorthe new operator Or, you must initialize every field before using them

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Fields Initialization NotesStructures and Enumerations 10C# 30

    Fields Initialization Notes For a class: For a class:

    You can define any constructor, including a parameter less oneparameter-less one

    Fields that are not initialized in the constructor, automatically get a default value at run timeautomatically get a default value at run time

    For a structure: You cannot define a parameter-less constructor All fields should be initialized in the constructors:

    The default provided parameter-less constructor assigns all fields with their default valuesTh il k th t ll d fi d t t The compiler makes sure that all user-defined constructors provide all fields with initial values

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Structures and Enumerations 11C# 30

    N ll bl TNullable Types

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    The Need for Nullable TypesStructures and Enumerations 12C# 30

    The Need for Nullable TypesReference types can have an value: n ll Reference types can have an value: null

    Sometimes it is necessary to mark aSometimes it is necessary to mark a Value type as nullor undefined A Boolean field in a database can store the values

    true or false, or it may contain neither

    NET 2 0 introd ces N llable T pes .NET 2.0 introduces Nullable Types C# 2.0 introduces convenient syntaxC# 2.0 introduces convenient syntax

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Nullable TypeStructures and Enumerations 13C# 30

    Nullable TypeN llable t pes can represent the al es Nullable types can represent the values of an underlying value type, and an y g ypadditional null valueTh N ll bl T t t The Nullable type exposes two public properties:p p p HasValue Set to true when the variable contains a

    non-null valuenon null value ValueIf HasValue is true, Valuecontains a

    meaningful value Otherwise it throws anmeaningful value. Otherwise, it throws an InvalidOperationException

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Using NullableStructures and Enumerations 14C# 30

    Using Nullable//Nullable Integerver 1 0//Nullable Integerver 1.0NullablenInt =newNullable(5);nInt =nInt +5;

    l i i ( )Console.WriteLine(nInt);...nInt =null;;if(nInt ==null){

    ......}if(nInt.HasValue){{

    ...}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Nullable ? ShorthandStructures and Enumerations 15C# 30

    Nullable ? Shorthand//Nullable Integerver 2 0//Nullable Integerver 2.0int?nInt =5; //int?isNullablenInt =nInt +5;

    l i i ( )Console.WriteLine(nInt);...nInt =null;;int?kInt =null;if(nInt ==kInt){{

    ...}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    GetValueOrDefault ??Structures and Enumerations 16C# 30

    GetValueOrDefault ??The GetVal eOrDefa lt method ret rns The GetValueOrDefault method returns the nullables value or the specified pdefault:publicTGetValueOrDefault(TdefaultValue);

    C# offers a short-hand for this method:

    publicTGetValueOrDefault(TdefaultValue);

    C# offers a short-hand for this method:int?x=null;int y=x??21;//y==21x=42;y=x??21;//y==42y x??21;//y 42

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Nullables SummaryStructures and Enumerations 17C# 30

    Nullables SummaryN llable t pes are sed to create al e Nullable types are used to create value types that can contain null as a valueyp The syntax T? is shorthand for System.Nullable The HasValue property returns true if the variable The HasValue property returns true if the variable

    contains a value, or false if it is nullThe Value property returns a value if one is assigned The Value property returns a value if one is assigned, or throws an exceptionTh d f lt l f ll bl t i bl t The default value for a nullable type variable sets HasValue to false. The Value is undefined

    This is a valid C# statement:int x=y>z?a??10:b??20;

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    int x y>z?a??10:b??20;

    Structures and Enumerations 18C# 30

    E iEnumerations

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Enumerations IntroductionStructures and Enumerations 19C# 30

    Enumerations IntroductionThe en meration concept in C# is similar The enumeration concept in C# is similar to the C/C++ enumerated type:yp Defining a set of symbolic names and integral values

    Using enums is recommended: Using enums is recommended: Improves readability and maintainability Improves type safety

    NET enums are first class citizens in the .NET enums are first-class citizens in the type system Enums derive from System.Enum, which derives from System.ValueType

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Enum DefinitionStructures and Enumerations 20C# 30

    Enum DefinitionenumFruit{

    Apple,Banana,Banana,Orange

    }//Dontprefixenumvalueswiththeenumname

    The default underlying type of an enumerator type is int but it can beenumerator type is int, but it can be defined to be any other integral typeenumFruit:byte //Thisdoesntmeanderives{

    Apple Apple,Banana,Orange

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }

  • Manipulating Enum ObjectsStructures and Enumerations 21C# 30

    Manipulating Enum Objects//Gettingallenum'snames//Gettingallenum snamesstring[]fruits=Enum.GetNames(typeof(Fruit));

    // f l t di l ll ibl ti//Usefultodisplayallpossibleenumoptionsforeach(stringfruitNameinfruits)

    Console.WriteLine(fruiteName);( )

    Console.WriteLine("Enteryourfavoritefruit:");try{try{

    strings=Console.ReadLine();//ConvertingasymbolintoanenuminstanceFruitf=(Fruit)Enum Parse(typeof(Fruit) s);Fruitf=(Fruit)Enum.Parse(typeof(Fruit),s);

    }catch(ArgumentException){

    C l W it Li ("S i lidf it")Console.WriteLine("Sorry,aninvalidfruit");}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Manipulating Enum ObjectsStructures and Enumerations 22C# 30

    Manipulating Enum Objects//Checkingifavalueisdefinedforanenum//Checkingifavalueisdefinedforanenumif(!Enum.IsDefined(typeof(Fruit),5))

    Console.WriteLine(5isnotdefined");

    //Gettingtheenumeratedtypeunderlyingtype.Console.WriteLine("TheunderlyingtypeofFruit:"+

    Enum.GetUnderlyingType(typeof(Fruit)));}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Bit Flag TypesStructures and Enumerations 23C# 30

    Bit Flag Types Enumerated types can also be used to Enumerated types can also be used to

    define bit flag types A bit flag enum can have multiple flags on and off

    A numeric value must be explicitlyA numeric value must be explicitly assigned to each symbol:[Fl ][Flags]enum Characteristics{

    Smart =0x0001, //Bit0setCalm =0x0002, //Bit1setTall =0x0004, //Bit2set, //Kind =0x0008, //Bit3setGentle =0x0010, //Bit4setGorgeous =0x001F //Allbitsset

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Gorgeous =0x001F //Allbitsset}

    Bit Flag Type Usage ExampleStructures and Enumerations 24C# 30

    Bit Flag Type Usage ExampleclassPersonclassPerson{

    publicPerson(stringname,Characteristicscharacter){{

    _name=name;_character=character;

    }}publicvoidSet(Characteristicscharacter){

    _character|= character;}publicoverridestringToString()pub c o e de st g oSt g(){

    return_name+"is:"+_character;}}privatestring_name;privateCharacteristics_character;

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }

  • Bit Flag Type Usage ExampleStructures and Enumerations 25C# 30

    Bit Flag Type Usage ExamplestaticvoidMain(){staticvoidMain(){

    Personjerry=newPerson("Jerry",Characteristics.Tall |Characteristics.Kind);

    C l W it Li (j )Console.WriteLine(jerry);

    jerry.Set(Characteristics.Gentle |Characteristics.Calm |Characteristics.Smart);

    Console.WriteLine(jerry);}}

    And the output is: Jerry is: Tall, KindJerry is: Gorgeous

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Bit Flags String FormattingStructures and Enumerations 26C# 30

    Bit Flags String FormattingEn m ToString() provided a comma Enum.ToString() provided a comma-separated list of set flagsp g

    There are two ways to get this behavior:1 Decorate the enum with the [Flags] attribute1. Decorate the enum with the [Flags] attribute2. Call the ToString() method on with an additional

    formater parameter Fformater parameter F

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Chapter SummaryStructures and Enumerations 27C# 30

    Chapter SummaryUser defined al e t pes User-defined value types Structs are:

    Derived from System.ValueType and sealed Have a pre-defined non-overridable parameterless ctor Can override Objects methods Can not be null (use Nullable)

    Enums are: Similar to C++ enums Define a scope for their constants values Have methods to show & parse strings May be marked with [Flags]

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel