C#-Object Oriented Programming

C#-Object Oriented Programming

memorize.aimemorize.ai (lvl 286)
Section 1

Preview this deck

Type Signature

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

4 years ago

Date created

Mar 1, 2020

Cards (62)

Section 1

(50 cards)

Type Signature

Front

AKA type annotation, defines the inputs and outputs for a function, subroutine or method. A type signature includes the function's return type, the number of arguments, the types of arguments, or errors it may pass back.

Back

If Statement

Front

The <test> must evaluate to a Boolean value for the code to compile, and the line of code that follows the statement is executed if <test> evaluates to true: if (<test>) { <code executed if <test> is true>; } else { <code executed if <test> is false>; }

Back

List the 14 simple types

Front

sbyte, byte, short, ushort, int, uint,long, ulong, float, double, decimal char, bool, string NOTE: Unlike complex types, cannot have children or attributes

Back

Switch Statement

Front

Similar to the IF statement, in that it executes code conditionaly based on the value of a test. However, switch enables you to test for multiple values of a test variable in one go, rather than just a single condition. -Limted to discrete values, rather than clauses such as "greater than X". switch (<testVar>) { case<comparisonVal1> : <code to execute if <testVar> == <comparisonVal1>> break; case<comparisonVal2> : <code to execute if <testVar> == <comparisonVal2>> break; ......... case<comparisonVarN>: <code to execute if <testVar>==<comparisonVarN>> break; } NOTE: It is illegal for the flow of execution to reach a second class statement after processing one case block.

Back

Delegate

Front

A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance. Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs. The following example shows a delegate declaration: public delegate int PerformCalculation(int x, int y); Any method from any accessible class or struct that matches the delegate type can be assigned to the delegate. The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes.

Back

Structs

Front

Data structures composed of several pieces of data, possibly of different types. They enable you to define your own types of variables based on this structure struct <typeName> { <memberDeclarations> } The <memberDeclarations> sectino contains declarations of variables (called the data members of the struct) in almost the same format as usual. Each member declaration takes the following form: <accessibility> <type> <name>; EX.) struct route { public orientation direction; public double distance; } NOTE: Structs are declared outside of the main body of the code, inside the namespace declaration

Back

Keywords with Method Definition

Front

virtual - The method can be overridden abstract-The method MUST be overridden in non-abstract derived classes (only permitted in abstract classes) override- The method overrides a base class method (it must be used if a method is being overridden). extern-The method definition is found elsewhere.

Back

Abstract (modifier)

Front

Indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events. Use the abstract modifier in a class declaration to indicate that a class is intended only to be a base class of other classes. Members marked as abstract, or included in an abstract class, must be implemented by classes that derive from the abstract class. Abstract classes have the following features: -An abstract class cannot be instantiated. -An abstract class may contain abstract methods and accessors. -It is not possible to modify an abstract class with the sealed (C# Reference) modifier because the two modifers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited. -A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors. -Use the abstract modifier in a method or property declaration to indicate that the method or property does not contain implementation. Abstract methods have the following features: -An abstract method is implicitly a virtual method. -Abstract method declarations are only permitted in abstract classes. -Because an abstract method declaration provides no actual implementation, there is no method body; the method declaration simply ends with a semicolon and there are no curly braces ({ }) following the signature.

Back

Name 5 Methods of System. Object

Front

Object() - Constructor for the System.Object type. ToString() - Returns a string corresponding to the object instance. By default, this is the qualified name of the class type, but this can be overridden to provide an implementation appropriate to the class type. GetType()-Returns the type of the object in the form of a System.Type object. GetHashCode()- Used as a hash function for objects where this is required. A hash function returns a value identifying the object state in some compressed form. Equals(object, object) - Compares the two objects passed to it and checks whether they are equal. This check is performed using the Equals(object) method. If both objects are null references, then this method returns true.

Back

Constructors

Front

When an object is first instantiated it needs to be initialized. This initialization is known as construction and is carried out by a constructor. -Called using the 'new' keyword. -Can be public or private. -Code external to a class can't instantiate an object using a private constructor; it must use a public constructor. This would force users of your classes to use a nondefault constructor (by making the default constructor private). DEFAULT CONSTRUCTOR Ex.) CupOfCoffee myCup = new CupOfCoffee(); -Parameter-less method with the same name as the class itself. NONDEFAULT CONSTRUCTOR Ex.)CupOfCoffee myCup = new CupOfCoffee("Blue Mountain"); -Constructor methods with parameters.

Back

List<T>

Front

Collection of type T objects List<T> myCollection = new List<T>(); An object instantiated using this syntax supports many methods, including: int Count void Add(T item) bool Remove (T item), etc.

Back

FOR Loops

Front

Executes a set number of times and maintains its own counter. for (<initialization>; <condition>; <operation>) { <code to loop> } NOTE: This works the same way as WHILE loop, but the formatting is easier code to read because the syntax involves the complete specification of the loop in one place, rather than dividing it over several statements in different areas of the code. -You can declare the counter variable as part of the for statement, however, the variable will not be accessible from code outside the loop

Back

FOREACH loop

Front

Enables you to address each element in an array using this simple syntax: foreach (<baseType> <name> in <array>) { //can use <name> for each element }

Back

Generics

Front

Make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot. Generics are most frequently used with collections and the methods that operate on them. Ex.) by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations. -Use generic types to maximize code reuse, type safety, and performance. -The most common use of generics is to create collection classes. -The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace. -You can create your own generic interfaces, classes, methods, events and delegates. -Generic classes may be constrained to enable access to methods on particular data types. -Information on the types that are used in a generic data type may be obtained at run-time by using reflection.

Back

Interface

Front

Collection of public instance (nonstatic) methods and properties that are grouped together to encapsulate specific functionality. After an interface has been defined, you can implement it in a class. This means that the class will then support all of the properties and members specified by the interface. -Normally prefixed with an I. -CANNOT exist on their own, CANNOT contain any code that implements its members; it just DEFINES the members. The implementation must come from the classes that implement the interface. -A class can support multiple interfaces, and multiple classes can support the same interface. -Good practice not to change it once published. If the interface changes later (ex. upgrade of underlying code) you should create a NEW interface that extends the old one.

Back

Inheritance

Front

Inheritance, together with encapsulation and polymorphism, is one of the three primary characteristics (or pillars) of object-oriented programming. -describes the ability to create new classes based on an existing class Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. A derived class can have only one direct base class. However, inheritance is transitive. If ClassC is derived from ClassB, and ClassB is derived from ClassA, ClassC inherits the members declared in ClassB and ClassA. NOTE: Structs do not support inheritance, but they can implement interfaces

Back

Partial Class Definitions

Front

Used for splitting the definition of a class across multiple files. This is an alternative to using #region/#endregion technique for code outlining/ decluttering code. -You can, for example, put the fields, properties, and ctor in one file, and the methods in another. -Interfaces applied to one partial class part apply to the whole class SYNTAX: public partial class MyClass { //code to run }

Back

Method

Front

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences. It is implicitly passed for the object for which it was called. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data).

Back

Destructors

Front

Used by the .NET Framework to clean up after objects. In general, code is not needed as the default operation does the work for you.

Back

Object

Front

Building block of an OOP app, encapsulates part of the app, which can be a process, a chunk of data, or a more abstract entity. -Contains properties and fields -Type of an object is known as a class, you can use class definitions to instantiate objects. -"Instance of a class" and "object" mean the same thing.

Back

Overloading Functions

Front

Provides you with the capability to create multiple functions with the same name, but each working with different parameter types. For example, a print function that takes a string (or char *) argument performs very different tasks than one that takes an argument of type double. Overloading permits uniform naming and prevents programmers from having to invent names such as print_sz or print_d.

Back

Keywords

Front

public- Members are accessible from any code private- Members are accesible only from code that is part of the class (the default if no keyword is used). internal- Members are accessible only from code within the assembly (project) where they are defined. protected - Members are accessible only from code that is part of either the class or a derived class.

Back

Static

Front

Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

Back

WHILE Loops

Front

Similar to DO loops, with one key difference: The Boolean test in a while loop takes place at the START of the loop cycle, not at the end. If the test evaluates to false, then the loop cycle is never executed while (<Test>) { <code to be looped> }

Back

Try...Catch....Finally

Front

try- Contains code that might throw exception catch- Contains code to execute when exceptions are thrown. Catch blocks can respond only to specific exception types (such as System.IndexOutOfRangeException) using <exceptionType>, hence the ability to provide multiple catch blocks. It is also possible to omit this parameter entirely, to get a general catch block that responds to all exceptions finally- Contains code that is ALWAYS executed, either after the try block if no exception occurs,afte a catch block if an exception is handled, or just before an unhandled exception moves "up the call stack".

Back

Array of Arrays

Front

AKA jagged array, "rows" may be different sizes.

Back

Arrays

Front

Indexed lists of variables stored in a single array type variable. They have a single base type- individual entries in an array are all of the same type Array entries are often referred to as elements. <baseType>[] <name; EX.) int[] myIntArray = {0,1,2,3,4,5};

Back

Static Constructor

Front

- Used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced. class SimpleClass { // Static variable that must be initialized at run time. static readonly long baseline; // Static constructor is called at most one time, before any // instance constructor is invoked or member is accessed. static SimpleClass() { baseline = DateTime.Now.Ticks; } } Static constructors have the following properties: -A static constructor does not take access modifiers or have parameters. -A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. -A static constructor cannot be called directly. The user has no control on when the static constructor is executed in the program. -A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file. -Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method. -If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running. -All nonstatic constructors are also known as instance constructors.

Back

Function

Front

Means of providing blocks of code that can be executed at any point in an application. A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value). All data that is passed to a function is explicitly passed.

Back

Dictionaries

Front

Keyed collections, whereby each item has an associated key. In this case, the key can be used to identify an item, rather than using the item's index. You can define a dictionary by implementing IDictionary or by deriving a class from DictionaryBase.

Back

Static Class

Front

- Basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the 'new' keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named UtilityClass that has a public method named MethodA, you call the method as shown in the following example: UtilityClass.MethodA(); -Best used with common code libraries.

Back

goto statement

Front

enables you to label lines of code and then jump straight to them using the goto statement. Pro: Simple way to control what code is executed when Con: Excessive use can result in spaghetti code

Back

Events

Front

Important occurrences that you can act on in other parts of code, similar to (but more powerful than) exceptions. -There is no equivalent to the try..catch structure for handling events. Instead, you must 'subscribe' to them. Subscribing to an event means supplying code that will be executed when an event is raised, in the form of an event handler. -Many handlers can be subscribed to a single event. -Event handlers are simply methods, only restriction on an event handler method is that it must match the return type and parameters required by the event.

Back

Overloaded Operator

Front

The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands. SYNTAX: type operator operator-symbol ( parameter-list ) NOTE: -Not all operators can be overloaded. See table located here: https://msdn.microsoft.com/en-us/library/8edha89s.aspx You can redefine the function of most built-in operators globally or on a class-by-class basis. Overloaded operators are implemented as functions.

Back

Containment

Front

One class contains another, similar to inheritance, but allows the containing class to control access to members of the contained class and even perform additional processing before using members of a contained class.

Back

Readonly

Front

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class. NOTE: The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants

Back

Collections

Front

Basically an array with bells and whistles, implemented as classes in much the same way as other objects. Often named in the plural form of the objects they store. Main difference from arrays is that collections usually implement additional functionality, such a Add() and Remove() methods to add and remove items to and from the collection.

Back

DO Loops

Front

The code you have marked out for looping is executed, a Boolean test is performed, and the code executes again if this test evaluates to true and so on. When the test evaluates to false, the loop exits do { <code to be looped> } while (<Test>);

Back

namespace

Front

These are the .NET way of providing containers for application code, such that code and its contents may be uniquely identified; also used as a means of categorizing items in the .NET framework. C# code, by default, is contained in the global namespace, meaning that items contained in this code are accessible from other code in the global namespace simply by referring to them by name.

Back

Members

Front

Classes and structs have members that represent their data and behavior. A class's members include all the members declared in the class, along with all members (except constructors and destructors) declared in all classes in its inheritance hierarchy. Private members in base classes are inherited but are not accessible from derived classes. Kinds of members a class or struct may contain: Fields Constants Properties Methods Events Operators Indexers Constructors Destructors Nested Types

Back

Encapsulation

Front

Encapsulation means that a group of related properties, methods, and other members are treated as a single unit or object. One of the three pillars of OOP. -Through encapsulation a class can hide the internal details of how an object does something. Encapsulation solves the problem at the implementation level. -A class or structure can specify how accessible each of its members (variables, properties, and methods) is to code outside of the class or structure. Encapsulation simplifies the interaction between objects. An object can use another object without knowing all its data or how its data is maintained. For example, a Client object might have name, address, company, and department properties. If a Bank object wants to use a Client object, it can request the name and address for the bank without needing to know the company and department details of the Client object. -With the help of encapsulation, a class can change the internal implementation without hurting the overall functionality of the system. -Encapsulation protects abstraction. PURPOSE: -To hide and prevent code (data) from the outside world (here the world means other classes and assemblies). -To prevent code (data) from accidental corruption due to programming errors so that we can deliver expected output. Due to programming mistakes, code may not behave properly and it has an effect on data and then it will affect the functionality of the system. With encapsulation we can make variables, properties, and methods private so it is not accessible to all but accessible through proper channels only to protect it from accidental corruption from other classes. -To have a class better control over its fields (validating values etc...).

Back

ternary operator

Front

aka conditional operator, works on three operands <test> ? <resultIfTrue> : <resultIfFalse> Good for simple statements.

Back

Polymorphism

Front

Means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways. It has two distinct aspects: -At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type. -Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed. "Fruit can be eaten, as a general rule, but different types of fruit is eaten in different ways. An apple, which is a fruit, can be eaten (because it is a fruit). A banana can also be eaten (because it is also a fruit), but in a different manner from an apple. You peal it first."

Back

Boxing

Front

The act of converting a value type into the System.Object type or to an interface type that is implemented by the value type. Unboxing is the opposite conversion. -The object created by boxing a variable in this way contains a reference to a copy of the value-type variable, not a reference to the original value-type variable.

Back

Multidimensional Arrays

Front

An array that uses multiple indices to access its elements. Said to be 'rectangular' because each "row" is the same size Two-dimensional array: <baseType>[,] <name>; Four-dimensional array: <baseType>[,,,]<name>; Arrays of more dimensions simple require more commas EX.) double[,] hillHeight = { {1,2,3,4}, {2,3,4,5}, {3,4,5,6} }; Although an array can have as many as 32 dimensions, it is rare to have more than three. NOTE: When you add dimensions to an array, the total storage needed by the array increases considerably, so use multidimensional arrays with care.

Back

Name the 3 Complex variable types

Front

Enums, structs, and arrays

Back

List the Operator Precedence from highest to lowest

Front

++,-- (used as prefixes); +,- (unary) *,/, % +, - =, *=, /=, %=, +=, -= ++, -- (used as suffixes)

Back

Access Modifiers for Class Definitions

Front

none -or- internal : Class is accessible only from within the current project public: Class is accessible from anywhere abstract -or- internal abstract: Class is accessible only from within the current project, and cannot be instantiated, only derived from. public abstract: Class is accessible from anywhere, and cannot be instantiated, only derived from sealed -or- internal sealed: Class is accessible only from within the current project, and cannot be derived from, only instantiated public sealed: Class is accessible from anywhere, and cannot be derived from, only instantiated.

Back

Enumerations

Front

Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast. enum <typeName> { <value1>, <value2>, <value3>, ...... <valueN> } NOTE: Enums are declared outside of the main body of the code, inside the namespace declaration

Back

Object-Oriented Programming

Front

Prior to OOP, functional/procedural programming often resulting in monolithic apps, all functionality contained in a few modules of code(often just one). OOP uses many more modules of code, with each offering specific funtionality. A modular method of programming gives you much more versatility and code reuse. OOP techniques are firmly rooted in the structure and meaning of data, and the interaction between that data and other data.. Usually means putting more effort into the design stages of a project, but has the benefit of extensibility.

Back

Section 2

(12 cards)

What is the difference between a constant and a read-only field?

Front

A constant: -Is static -Assigned on the declaration -Assigned to an expression that is fully evaluated at compile time. A read-only field: -Can be static or non-static -Assigned in the declaration or the constructor -Assigned to any valid expression

Back

Dictionary<K,V>

Front

Enables you to define a collection of key-value pairs. EX.) Dictionary<string, int> things = new Dictionary<string,int>(); things.Add("Green Things", 29); things.Add("Red Things", 45); things.Add("Yellow Things", 57); things.Add("Blue Things", 32);

Back

What is the difference between a property and a method?

Front

-Properties are the gatekeepers, providing access to the data. -Methods are the operations

Back

When should you use a read-only field?

Front

When defining a field that is initialized from a file, table or code but should not then be changed anywhere else in the application.

Back

What is the difference between a static class and a singleton?

Front

-Static class cannot be instantiated -Singleton can instantiate itself and provide that instance to other code that needs it, so a singleton can still leverage OOP techniques

Back

What are auto-implemented properties?

Front

-Short cut syntax for defining an implicit backing field with its associated property getter and setter

Back

When should you use an auto-implemented property?

Front

When creating simple properties for a class

Back

Explain the data encapsulation principal

Front

-An object's data should be accessible only to that object. -Backing fields containing the object data should be marked as private

Back

What is the primary purpose of a property?

Front

-To guard access to the fields in the class -And optionally provide a location for logic that is executed when getting or setting a field value

Back

When shouldn't you use an auto-implemented property?

Front

If the property requires any code in the getter or setter.

Back

Singleton

Front

A class that provides a single instance of itself

Back

What is lazy loading, and when would you use it?

Front

-Instantiating related objects when they are needed, and not before. This often involves creating the instance in the property getter for the related object, that way when any code requests the instance it is created as needed.

Back