Week 1 Day 3

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Type-testing and cast operators - 'is' operator

The is operator checks if the runtime type of an expression result is compatible with a given type. "E is T" returns true if E is nonnull and can be converted to type T by a reference, a boxing, or an unboxing conversion.

Access Modifiers - Public

The public keyword is an access modifier for: •types and •type members. There are no restrictions on accessing public members.

Inheritance and Access Modifiers

Access Modifiers affect inheritance •Private -members are visible only in derived classes that are nested in their base class. •Protected - visible only in derived classes. •Internal - visible only in the same assembly as the base class. •Public - visible in derived classes and are part of the derived class' public interface. •Members of a base class that are NOT inherited by derived classes. a) Static constructors - Which initialize the static data of a class. b) Instance constructors - Each class must define its own constructors

Class - Member Accessibility

Access Modifiers control the regions of program text that can access the member. • private - This class only. • protected - derived classes. • private protected - This class or derived classes only. • internal - current assembly (.exe, .dll). • protected internal - This class, child classes, or classes within the same assembly. • public - Access isn't limited.

Access Modifiers - Class Member Accessibility

Access Modifiers control which regions of program text can access the member. • public - Access isn't limited. • private (default)- This class only. • internal - current assembly (.exe, .dll). • protected - This class and through an instance of derived class in the derived class itself. • protected internal - Child classes, or classes within the same assembly. • private protected - This class or derived classes only.

Modifiers - Override

Classes The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event. ALL Override Members... • provides a new implementation of an inherited method • must have the same signature as the inherited method. • Both methods must be virtual, abstract, or override. • You cannot use the static, or virtual modifiers to modify an override method.

Class

Classes are defined using class declarations. A class declaration starts with a header that specifies • the attributes and modifiers of the class, • the name of the class, • the base class (if given), and • the interfaces implemented by the class. The header is followed by the class body, which consists of a list of member declarations written between curleyBrackets { }.

Generics

Generics let you tailor a method, class, structure, or interface to the precise data type it acts upon. When you create an instance of a generic class, you specify the types to substitute for the type parameters. This establishes a new generic class, referred to as a constructed generic class, with your chosen types substituted everywhere that the type parameters appear. The result is a type-safe class that is tailored to your choice of types.

Explicit Conversion

If there is a risk of losing information, you must perform a Cast. Specify the target type in ( ) in front of the value or variable to be converted. *This doesn't prevent the loss of data. An explicit cast is required if you need to convert from a base type to a derived type.

Implicit Conversion

Implicit conversion is possible in: • numeric types when the value to be stored can fit into the variable memory without being truncated. • integral types when the range of the source type is at least as big as the target type. Implicit conversion is always possible in reference types. • When a class is converted to any one of its direct or indirect base classes or interfaces. • No special syntax is necessary. • Derived classes always contain all the members of the base class.

Type conversion exceptions at run time

In some reference type conversions, It is possible for a cast operation that compiles correctly to fail at run time. A type cast that fails at run time will cause an InvalidCastException to be thrown.

Inheritance

Inheritance allows you to define a child class that reuses (inherits) the characteristics of a parent class. The class that Inherits the members of the 'base' class is called the 'derived' class. • structs, delegates, and enums do not support inheritance. IS-A relationship

Class - Instance Instantiation

Instances of classes are created using the new operator, which • allocates memory for a new instance, • invokes a constructor to initialize the instance • returns a reference to the instance. The memory occupied by an object is automatically reclaimed by the GC when the object is no longer reachable

Generics - Instantiation

On instantiation of a generic class, specify the actual types to substitute for the type parameters. This establishes a 'constructed generic class', with your chosen types substituted everywhere that the type parameters appear. The result is a type-safe class that is tailored to your choice of types.

Class - Value, Reference, Output, and Array Parameters

Parameters are used to receive values or variable references from method calls. There are four types: 1. value parameter • a copy of the argument passed. Changes don't affect the original argument. Can be options by specifying a default value. 2. reference parameter • declared with the 'ref' modifier. Used for passing arguments by reference. The argument must be a variable with a definite value. Changes take place on the original value. 3. output parameter - declared with the out modifier. Used for passing arguments by reference. An explicitly assigned value is not required before the method call. 4. parameter array - permits a variable number of arguments to be passed to a method. Declared with the params modifier. Must be the last parameter and be a 1-D array. Write() and WriteLine() methods use parameter arrays.

Polymorphism

Polymorphism is the ability to store a reference to a child class object in a parent class variable. This allows us to upcast if we want to change the child class object to the type of the parent class.

Inheritance - Types

Single inheritance(C#) - where subclasses inherit the features of one superclass. A class acquires the properties of another class Multilevel inheritance(C#) - where a subclass is inherited from another subclass. Hierarchical inheritance(C#) - where one class serves as a superclass (base class) for more than one sub class Multiple inheritance(NOT IN C#) - one class can have more than one superclass and inherit features from all parent classes. Hybrid inheritance(NOT IN C#) - a mix of two or more types of inheritance

Modifiers - Static

Static CLASSES... • Cannot be instantiated or extended. • If a class is static, all It's members must be static. • Essentially, just a container for static members. ALL Static Members... • Cannot use this to reference static methods or property accessors. • Belongs to the class type itself rather than the specific object instance. • A static member is referenced through the type name. (ex. Class.Struct.prop)

Generic Collections

The .NET class library provides a number of strongly-typed generic collection classes in the System.Collections.Generic and System.Collections.ObjectModel namespaces Many generic collection types are direct analogs of nongeneric types. •Dictionary<TKey,TValue> is a generic version of Hashtable. •List<T> is a generic version of ArrayList. •Queue<T> and Stack<T> classes that correspond to the nongeneric versions. •There are generic and nongeneric versions of SortedList<TKey,TValue>. Both versions are hybrids of a dictionary and a list. Unique Generic Structures •The SortedDictionary<TKey,TValue> generic class is a pure dictionary and has no nongeneric counterpart. •The LinkedList<T> generic class is a true linked list and has no nongeneric counterpart.

Type-testing and cast operators - 'as' operator

The as operator explicitly converts the result of an expression to a given reference or nullable value type. If the conversion is not possible, the as operator returns null. Unlike the cast operator (), the as operator never throws an exception. "E as T" produces the same result as " E is T ? (T)(E) : (T)null" The as operator considers only reference, nullable, boxing, and unboxing conversions. You cannot use the as operator to perform a user-defined conversion. To do that, use the cast operator ().

Boxing and Unboxing (General)

The concept of boxing and unboxing underlies the C# Unified Type System in which a value of any type can be treated as an object.

Object-Oriented Programming - Four Pillars

The four pillars of OOP • Abstraction : The process of showing only essential/necessary features of an entity/object to the outside world and hide the other irrelevant information. • Encapsulation : Wrapping data and member functions (Methods) together into a single unit (class). Encapsulation automatically achieves the concept of data hiding. This provides security to data by making variables private and allowing public methods access to the private variables. • Inheritance : Creating a new class from an existing class template. A class (subclass) acquires the properties and behavior of a 'base' ('super') class. • Polymorphism: "many forms". A subclass can inherit functionalities or behavior of its parent/base class and define its own unique behavior.

Type-testing and cast operators - 'is' operator

The is operator takes into account boxing and unboxing conversions but doesn't consider numeric conversions.

Modifiers - Sealed

The sealed modifier prevents inheritance from a class. The sealed modifier prevents an overriding method from being overridden by a more derived method. When should you use Sealed? Consider... • The potential benefits that deriving classes might gain through the ability to customize your class. • The potential that deriving classes could modify your classes in such a way that they would no longer work correctly or as expected.

typeof Operator

The typeof operator obtains the System.Type instance type. The argument to the typeof operator must be the name of a type or a type parameter. •An expression cannot be an argument of the typeof operator. To get the System.Type instance for the runtime type of an expression result, use Object.GetType(). •Use the typeof operator to check if the runtime type of the expression result exactly matches a given type.

Modifiers - Virtual

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. The implementation of a virtual member can be changed by an overriding member in a derived class. •By default, methods are nonvirtual. You cannot override a non-virtual method. •You cannot use the virtual modifier with the static, abstract, private, or override modifiers. •A virtual inherited property can be overridden by using the override modifier.

Casting and Type Conversion

There are 2 types of conversions in C#: •Implicit conversions: No special syntax. Type safe. No data loss. •Explicit conversions (casts): Explicit conversions require the cast operator (). A cast is required when data might be lost in the conversion, or when failure could occur.

Class - Members

There are two categories of class members. •static - belong to classes •instance - belong to objects (instances of classes). The categories of members a class: • Constructors - To initialize instances of the class • Constants - Constant values • Fields - Variables • Methods - Computations/actions that can be performed • Properties - Fields combined with the actions associated with reading/writing them • Types - Nested types declared by the class

Class - Methods

There are two categories of methods: • Static - accessed directly through the class • Instance - accessed though instances of a class. Methods have a Method Signature which consists of: • the name of the method, • The (optional) type parameters, • its parameters.

Class - Type Parameters

Type Parameters • are used to define a generic class type. • follow the class name and are inside < >. • are used to define the members of the class.

Unboxing

Unboxing extracts the value type from the object. Unboxing is explicit. Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of: • Checking the object instance to make sure that it is a boxed value of the given value type. • Copying the value from the instance into the value-type variable.

Partial Classes, Structs, Interfaces

You can split the definition of a class, a struct, an interface or a method over two or more source files. Each source file contains a section. All parts are combined on compilation. When would you do this? • When working with automatically generated source code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio. • Attributes, inherited classes, etc, are merged at compile time.

Modifiers - Abstract

abstract means the thing being modified has a missing or incomplete implementation. • intended only to be a base class of other classes, • NOT instantiated on their own. • classes, methods, properties, indexers, and events can be abstract • Members marked as abstract must be implemented by non-abstract classes that derive from the abstract class.

Class - Static and Instance Methods

static method - • declared with a static modifier. • doesn't operate on a specific class instance. • can only directly access static members. • Cannot use 'this' instance method - • declared without the static modifier. • operates on a specific class instance only. • can access both static and instance members. • Can use 'this'.

Stack<T>

• A (LIFO) collection of instances of the same specified type. • Stack<T> is implemented as an array. • Stacks (and Queues) are useful when you need temporary storage for information • Use Stack<T> if you need to access the information in reverse order. • Use System.Collections.Concurrent.ConcurrentQueue<T> when access is needed from multiple threads concurrently. • System.Collections.Generic.Stack<T> preserves variable states during calls to other procedures. • The capacity can be decreased by calling .TrimExcess(). • Stack<T> accepts null as a valid value for reference types and allows duplicate elements. • Three main operations can be performed on a System.Collections.Generic.Stack<T> and its elements: a) Push() inserts an element at the top of the Stack<T>. b) Pop() removes an element from the top of the Stack<T>. c).Peek() returns an element that is at the top of the Stack<T> but does not remove it from the Stack<T>.

Access Modifiers - Private Protected

• A private protected member is accessible by types derived from the containing class, but only within its containing assembly.

Abstract METHODS

• An abstract method is implicitly a virtual method. • are only permitted in abstract classes. • do not have { } or method body • only have implementation in derived class methods using override. • Cannot have static or virtual modifiers

Interface

• An interface defines a contract that can be implemented by classes and structs. • An interface can contain methods, properties, events. • An interface does NOT provide implementations. It specifies the members that must be implemented by classes or structs that implement the interface. • Interface implementation is NOT inheritance. It is intended to express a "can do" relationship between an interface and its implementing type. • Interfaces are used to simulate multiple inheritance. Interfaces may employ multiple inheritance. Classes and structs can implement multiple interfaces

Abstract PROPERTIES

• Everything with methods is true for properties. • Abstract properties are written with { } but still do NOT have an implementation

Queue<T>

• FIFO - Objects stored in a Queue<T> are inserted at one end and removed from the other. • Use Queue<T> if you need to access the information in the same order that it is stored in the collection. • Use ConcurrentQueue<T> if you need to access the collection from multiple threads concurrently. • Queue<T> accepts null as a valid value for reference types and allows duplicate elements. • Queues and stacks are useful when you need temporary storage for information • Three main operations can be performed on a Queue<T> and its elements: a) Enqueue adds an element to the end of the Queue<T>. b) Dequeue removes the oldest element from the start of the Queue<T>. c) Peek peek returns the oldest element that is at the start of the Queue<T> but does not remove it from the Queue<T>.

List<T>

• List<T> represents a strongly typed list of objects • Elements can be accessed by (zero based) index[]. • Provides methods to search, sort, and manipulate lists. • The List<T> class is the generic equivalent of the (Deprecated) ArrayList class. • It implements the IList<T> generic interface by using an array whose size is dynamically increased as required. • The List<T> is not guaranteed to be sorted. • Use a 'content initializer' to add content of the specified type. • Use 'foreach' to iterate through the List. • Add content using .Add(). • Use 'foreach' to iterate through the List

SortedList<TKey,TValue>

• Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation. • SortedList<TKey,TValue> is implemented as an array of key/value pairs, sorted by the key. • SortedList<TKey, TValue>is similar to the SortedDictionary<TKey,TValue> generic class a) SortedList<TKey,TValue> uses less memory than SortedDictionary<TKey,TValue>. b) SortedDictionary<TKey,TValue> has faster insertion and removal operations for unsorted data. c) If the list is populated all at once from sorted data, SortedList<TKey,TValue> is faster than SortedDictionary<TKey,TValue>. d) SortedList<TKey,TValue> supports efficient indexed retrieval of keys and values • The capacity can be decreased by calling .TrimExcess() or by setting the Capacity property explicitly. • The 'foreach' statement is a wrapper around the enumerator. It is readonly

Generics - What qualifies as a generic method?

•A method is generic only if it has its own list of type parameters. •Generic methods can appear on generic or nongeneric types. •A method is not generic just because it belongs to a generic type, or even because it has formal parameters whose types are the generic parameters of the enclosing type.

Access Modifiers - Protected Internal

•A protected internal member of a base class is accessible from any type within its containing assembly. •It is also accessible in a derived class located in another assembly only if the access occurs through a variable of the derived class type. •Struct members cannot be protected internal (because structs cannot be inherited).

Access Modifiers - Class Accessibility

•Classes and structs declared directly within a namespace (not nested within other classes or structs) can only be either public or internal. •Internal is the default. •Derived classes can't have greater accessibility than their base classes.

Modifiers - Const

•Const fields and locals aren't variables and may not be modified. •Const fields can be numbers, Boolean, strings, or null. •The only reference types that can be const are string and a null reference. •The static modifier is not allowed in a const declaration.

Access Modifiers - Private

•Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared. •Nested types in the same body can also access those private members.

Modifiers - readonly

•The initialization can only occur as part of the declaration or in a constructor in the same class. •Like const, but initialization can be deferred until it's constructor finishes.

Access Modifiers - Internal

Internal types and members are accessible only within files in the same assembly. A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code.

Class - Base Classes

A class declaration specifies an inherited base class by following the class name and type parameters with... : [baseClassName]

Access Modifiers - Protected

A protected member is accessible through derived class instances when the derived class instance is inside the derived class itself.

Abstraction

Abstraction is the process by which a developer separates the relevant data from the irrelevant details in order to simplify use. Abstraction in daily life • Apartment Building. We determine what the building is for by it's exterior or sign but don't know the specifics as to how the people live. • Factory. • Snail Mail.

Boxing

Boxing happens when any value type is cast to an object. The value is wrapped to give it reference type behavior. Boxing is implicit. Boxing to the object type allows different types to inhabit the same array.

Class - Local Variables

Local variables - declared inside the body of the method. They must have a type name and a variable name. All variables get a default value. •Int == 0; •String == "";

Encapsulation

Encapsulation the restricting of direct access to abstracted data. Encapsulation prevents unauthorized parties' direct access to the members of a class. Publicly accessible methods are generally provided in the class (socalled "getters" and "setters") to access the values.

Accessibility of Classes

Classes and structs declared directly within a namespace (not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified. Derived classes can't have greater accessibility than their base types.

Class - Method Overloading

Method overloading • permits multiple methods in the same class to have the same name • Methods must each have unique parameter lists. • The compiler uses 'overload resolution' to determine the specific method to invoke. • 'Overload resolution' finds the one method that best matches the arguments or reports an error if none is found. • A method can be selected by explicitly casting the arguments to the exact parameter types.

Dictionary<TKey,TValue>

• Represents a collection of key/value pairs. • The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. A key and its value must be added at the same time. • A key cannot be null, but a value can be, if its type TValue is a reference type. • As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array The foreach statement returns an object representing the key/value pair in the collection. Since the Dictionary<TKey,TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair<TKey,TValue> of the key type and the value type. The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it

C# Array Class

• The Array class is considered a collection because it is based on the IList interface. • It has methods for creating, manipulating, searching, and sorting arrays, • length, and data type are set when the array instance is created and cannot be changed. • An array can be Single-Dimensional, Multidimensional or Jagged. • Numeric default values are zero (0). • Reference default values are 'null'. • Arrays are 'zero indexed' (They start at 0).

Abstract CLASSES

• cannot be instantiated. • may contain abstract methods and accessors. • must provide implementation for all interface members. • Cannot include the sealed modifier.

Generics - Terminology

• generic type definition - a class, structure, or interface declaration that functions as a template with placeholders for its types. • generic type parameters - type parameters. Placeholders in a generic type or method definition. Conventionally named <T>. • constructed generic type - constructed type. The result of specifying types for the generic type parameters of a generic type definition. • generic type argument - any type that is substituted for a generic type parameter. • generic type - constructed types and generic type definitions. • constraints - limits placed on generic type parameters. Arguments that do not satisfy the constraints cannot be used. • generic method definition - a method with two parameter lists: a list of generic type parameters and a list of formal parameters. Type parameters can appear as the return type or as the types of the formal parameters.


Kaugnay na mga set ng pag-aaral

11.6.13 Redundancy and High Availability

View Set

Renewable Energy Systems Midterm 1

View Set

Chapter 4 - Explain the accrual basis of accounting and the reasons for adjusting entries.

View Set

EAQ Fluid and Electrolytes - Concept

View Set