C# Completecurse

¡Supera tus tareas y exámenes ahora con Quizwiz!

the syntax for a derived class.

A colon and the name of the base class follow the name of the derived class.

Add(T t)

Adds an element t to the end of the list.

Add(K key, V value)

Adds an element with a specific key, value pair into the sorted list.

There are three ways to pass arguments to a method when the method is called:

By value, By reference, and as Output.

Static Constructors

Constructors can be declared static to initialize static members of the class. The static constructor is automatically called once when we access a static member of the class.

Dictionary<K, V> properties include:

Count - Gets the number of key/value pairs contained in the dictionary. Item[K key] - Gets the value associated with the specified key in the dictionary. Item is the indexer and is not required when accessing an element. You only need to use the brackets [] and key value. Keys - Gets an indexed collection containing only the keys contained in the dictionary.

Stack<T> properties include:

Count - Returns the number of elements in the stack.

Pass by reference copies an argument's memory address into the formal parameter.

Inside the method, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

Adding comments to your code is good programming practice.

It facilitates a clear understanding of the code for you and for others who read it.

String objects support a number of useful properties and methods:

Length IndexOf(value) Insert(index, value) Remove(index) Replace(oldValue, newValue) Substring(index, length) Contains(value).

Array Methods

Max returns the largest value. Min returns the smallest value. Sum returns the sum of all elements.

Can you inherit from a struct?

No

Stacks can be used to

create undo-redo functionalities, parsing expressions (infix to postfix/prefix conversion), and much more.

Also called auto-properties, they allow for

easy and short declaration of private members.

What's the difference between ++x and x++?

++x increments x's value before using it x++ uses x's value then increments it

The System.Collections namespace includes the following non-generic collections:

- ArrayList - SortedList - Stack - Queue - Hashtable - BitArray

In summary, the benefits of encapsulation are:

- Control the way data is accessed or modified. - Code is more flexible and easy to change with new requirements. - Change one part of code without affecting other parts of code.

Methods have many advantages, including:

- Reusable code. - Easy to test. - Modifications to a method do not affect the calling program. - One method can accept many different inputs.

But why use interfaces rather than abstract classes?

A class can inherit from just one base class, but it can implement multiple interfaces! Therefore, by using interfaces you can include behavior from multiple sources in a class.

do-while

A do-while loop is similar to a while loop, except that a do-while loop is guaranteed to execute at least one time.

Queue<T>

A queue is a First In, First Out (FIFO) collection of elements where the first element that goes into a queue is also the first element that comes out.

SortedList<K, V>

A sorted list is a collection of key/value pairs that are sorted by key. A key can be used to access its corresponding value in the sorted list.

Stack<T>

A stack is a Last In, First Out (LIFO) collection of elements where the last element that goes into the stack will be the first element that comes out.

SortedList<K, V> methods include:

Add(K key, V value) - Adds an element with a specific key, value pair into the sorted list. Remove(K key) - Removes the element with the specific key, value pair associated with the specified key from the sorted list.

Dictionary<K, V> methods include:

Add(K key, V value) - Adds the key, value pair to the dictionary. Remove(K key) - Removes the key/value pair related to the specified key from the dictionary.

HashSet<T> methods include:

Add(T t) Adds a value (t) to the hash set. IsSubsetOf(ICollection c) Returns true if the hash set is a subset of the specified collection (c).

AddRange(IEnumerable coll)

Adds the elements of collection coll with elements of the same type as List<T> to the end of the list. IEnumerable is the collections interface that supports simple iteration over the collection.

Static Classes

An entire class can be declared as static. A static class can contain only static members.

Indexers

An indexer allows objects to be indexed like an array.

The else Clause

An optional else clause can be specified to execute a block of code when the condition in the if statement evaluates to false. Remember that all else clauses must have corresponding if statements.

The following methods are available in the File class:

AppendAllText() - appends text to the end of the file. Create() - creates a file in the specified location. Delete() - deletes the specified file. Exists() - determines whether the specified file exists. Copy() - copies a file to a new location. Move() - moves a specified file to a new location

As you can see, we can access the static variable using the class name:

Cat.count. The count variable is shared between all Cat objects. For this class, each time an object is created, the static value is incremented. The program above demonstrates this when 2 is displayed after creating two objects of that class.

Static Now it's time to discuss the static keyword. You first noticed it in the Main method's declaration:

Class members (variables, properties, methods) can also be declared as static. This makes those members belong to the class itself, instead of belonging to individual objects. No matter how many objects of the class are created, there is only one copy of the static member.

Here are additional Queue<T> methods:

Clear() - Removes all objects from the queue. Contains(T t) - Returns true when the element t is present in the queue. Peek() - Returns the object at the beginning of the queue without removing it. ToArray() - Copies the queue into a new array.

Here are additional Stack<T> methods:

Clear() - Removes all the elements from the stack. Contains(T t) - Returns true when the element t is present in the stack. ToArray() - Copies the stack into a new array.

not inherited

Constructors are called when objects of a class are created. With inheritance, the base class constructor and destructor are not inherited, so you should define constructors for the derived classes. However, the base class constructor and destructor are being invoked automatically when an object of the derived class is created or deleted.

Queue<T> properties include:

Count - Gets the number of elements in the queue.

SortedList<K, V> properties include:

Count - Gets the number of key/value pairs contained in the sorted list. Item[K key] - Gets or sets the value associated the specified key contained in the sorted list. Item is the indexer and is not required when accessing an element. You only need to use the brackets [] and the key, value. Keys - Gets a sorted and indexed collection containing only the keys in the sorted list.

List<T> properties and methods include:

Count A property that gets the number of elements contained in the list. Item[int i] Gets or sets the element in the list at the index i. Item is the indexer and is not required when accessing an element. You only need to use the brackets [] and the index value inside the brackets. Add(T t) Adds an element t to the end of the list. RemoveAt(int index) Removes the element at the specified position (index) from the list. Sort() Sorts elements in the list.

HashSet<T> properties include:

Count Returns the number of values in the hash set.

BitArray methods include:

Get(int i) - Gets the value of the bit at a specified position i in the bit array. Set(int i, bool value) - Sets the bit at a specified position i to a specified value in the bit array. SetAll(bool value) - Sets all the bits to a specified value in the bit array. And(BitArray ba) - Performs the bitwise AND operation on the elements of the bit array object with a specified bit array ba. Or(BitArray ba) - Performs the bitwise OR operation on the elements of the bit array and the specified bit array ba. Not() - Inverts the bit values of the bit array. Xor(BitArray ba) - Performs the bitwise XOR operation on the elements of the current bit array object and the elements in the specified bit array ba.

Values

Gets a sorted and indexed collection of the values in the sorted list.

Item[int i]

Gets or sets the element in the list at the index i. Item is the indexer and is not required when accessing an element. You only need to use the brackets [] and the index value inside the brackets.

Item[K key]

Gets or sets the value associated the specified key contained in the sorted list. Item is the indexer and is not required when accessing an element. You only need to use the brackets [] and the key, value.

Count

Gets the number of key/value pairs contained in the sorted list.

Structs vs Classes

In general, classes are used to model more complex behavior, or data, that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created. Consider defining a struct instead of a class if you are trying to represent a simple set of data.

Strings

It's common to think of strings as arrays of characters. In reality, strings in C# are objects.

Operator Overloading

Most operators in C# can be overloaded, meaning they can be redefined for custom actions.

our whole program is inside a namespace. So, what are namespaces?

Namespaces declare a scope that contains a set of related objects. You can use a namespace to organize code elements. You can define your own namespaces and use them in your program.

Can you instantiate objects of an abstract class?

No

In this case, we declared a public member variable count, which is static. The constructor of the class increments the count variable by one.

No matter how many Cat objects are instantiated, there is always only one count variable that belongs to the Cat class because it was declared static.

Here are additional HashSet<T> methods:

Remove(T t) Removes the value (t) from the hash set. Clear() Removes all the elements form the hash set. Contains(T t) Returns true when a value (t) is present in the hash set. ToString() Creates a string from the hash set. IsSupersetOf(ICollection c) Returns true if the hash set is a superset of the specified collection. UnionWith(ICollection c) Applies set union operation on the hash set and the specified collection (c). IntersectWith(ICollection c) Applies set intersection operation on the hash set and the specified collection (c). ExceptWith(ICollection c) Applies set difference operation on the hash set and the specified collection (c).

Clear()

Removes all the elements from the sorted list.

RemoveAt(int index)

Removes the element at the specified position (index) from the list.

Remove(K key)

Removes the element with the specific key, value pair associated with the specified key from the sorted list.

Remove(T t)

Removes the first occurrence of the object t from the list.

String.concat()

Returns a new string with this string concatenated with another string; Can also use + to achieve the same result Return Type: String combines the two strings

IndexOf(T t)

Returns the index of the first occurrence of the element t in the list.

Contains(T t)

Returns true if the specified element t is present in the list.

String.equals()

Returns true if two strings are equal; Otherwise returns false Return Type: boolean

ContainsValue(V value)

Returns true when a specified value is present in the sorted list.

ContainsKey(K key)

Returns true when the specified key is present in the sorted list.

Reverse()

Reverses the order of the elements in the list.

TrimExcess()

Sets the capacity to the actual number of elements in the list. This is useful when trying to reduce memory overhead.

Sort()

Sorts elements in the list.

As discussed earlier, a string variable is actually an object of the

String class. Further, the String class is actually an array of Char objects. In this way, the string class implements an indexer so we can access any character (Char object) by its index

All public members of Animal become public members of Dog.

That is why we can access the Legs member in the Dog constructor. Now we can instantiate an object of type Dog and access the inherited members as well as call its own Bark method.

The ? : Operator

The ?: operator works the following way: Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire expression. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

The if Statement

The if statement is a conditional statement that executes a block of code when a condition is true.

What do you think, is there a difference between while(num++ < 6) and while(++num < 6)?

The loop while(++num < 6) will execute 5 times, because pre-increment increases the value of x before checking the num < 6 condition, while post-increment will check the condition before increasing the value of num, making while(num++ < 6) execute 6 times.

The readonly Modifier

The readonly modifier prevents a member of a class from being modified after construction. It means that the field declared as readonly can be modified only when you declare it or from within a constructor.

To pass the value by reference, the ref keyword is used in both the call and the method definition:

The ref keyword passes the memory address to the method parameter, which allows the method to operate on the actual variable. The ref keyword is used both when defining the method and when calling it.

The break Statement

The role of the break statement is to terminate the switch statement. All case and default code must end with a break statement.

It is not possible to modify an abstract class with the sealed modifier because the two modifiers have opposite meanings.

The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

switch

The switch statement provides a more elegant way to test a variable for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Parameters behave within the method similarly to other local variables.

They are created upon entering the method and are destroyed upon exiting the method.

Note the parentheses after the WriteLine method.

This is the way to pass data, or arguments, to methods. In our case WriteLine is the method and we pass "Hello World!" to it as an argument.

the empty parentheses in the ReadLine method.

This means that it does not take any arguments.

Declaring Methods

To use a method, you need to declare the method and then call it.

When overloading methods, the definitions of the methods must differ from each other by the types and/or number of parameters.

When there are overloaded methods, the method called is based on the arguments. An integer argument will call the method implementation that accepts an integer parameter. You cannot overload method declarations that differ only by return type.

So, why use properties? Why not just declare the member variable public and access it directly?

With properties you have the option to control the logic of accessing the variable.

C# supports nested classes:

a class that is a member of another class.

The class defines a data type for objects, but it is not an object itself. An object is

a concrete entity based on a class, and is sometimes referred to as an instance of a class.

An array is

a data structure that is used to store a collection of data. You can think of it as a collection of variables of the same type.

a class is

a data type that defines a set of variables and methods for a declared object.

Objects aren't always representative of just physical characteristics. For example, a programming object can represent

a date, a time, and a bank account. A bank account is not tangible; you can't see it or touch it, but it's still a well-defined object because it has its own properties.

A recursive method is

a method that calls itself.

Unlike classes, structs can be instantiated without using

a new operator.

The interface simply describes what a class should do. The class implementing the interface must define how to

accomplish the behaviors.

The property is accessed by its name, just like

any other public member of the class.

AppendAllText()

appends text to the end of the file.

Structs share most of the same syntax as classes, but

are more limited than classes.

Parameters

are variables that accept the values passed into the method when called.

We can also use a loop to read the values of an

array.

Once the property is defined, we can use it to

assign and read the private member

Now, upon the creation of an object of type Person, the constructor is

automatically called.

As constructors are used when a class is instantiated, destructors are

automatically invoked when an object is destroyed or deleted.

This method accepts an integer argument only. Overloading it will make it

available for other types, such as double: Now, the same Print method name will work for both integers and doubles.

An abstract class is intended to be a

base class of other classes. It acts like a template for its derived classes.

One of the classic tasks that can be solved easily by recursion is

calculating the factorial of a number.

Copy()

copies a file to a new location.

Create()

creates a file in the specified location.

We can provide initial values to the array when it is declared by using

curly brackets: string[ ] names = new string[3] {"John", "Mary", "Jessica"};

Exception handling is particularly useful when

dealing with user input.

You access all members of the Math class using the class name, without

declaring an object.

Inheritance allows us to

define a class based on another class.

Note the brackets in the syntax <T>, which are used to

define a generic type.

Note the square brackets used to

define the number of elements the array should hold.

Postfix

evaluates the expression and then performs the incrementing. The postfix example assigns the value of x to y, and then increments x.

Generic collections are the preferred type to use as long as

every element in the collection is of the same data type. Only desired data types can be added to a generic collection and this is enforced by using strong typing which reduces the possibility of errors.

An optional finally block can be used after the catch blocks. The finally block is used to

execute a given set of statements, whether an exception is thrown or not.

The HashSet<T> class provides high-performance set operations. HashSets allow

fast lookup, addition, and removal of items, and can be used to implement either dynamic sets of items or lookup tables that allow finding an item by its key (e.g., finding the phone number of a person by the last name).

float

floating point number.

The Length property can be useful in

for loops where you need to specify the number of times the loop should run.

Which accessor is used to read the value of a member?

get

You can have any custom logic with

get and set accessors.

the indexer definition includes the this keyword and an index, which is used to

get and set the appropriate value.

A collection is used to

group related objects. Unlike an array, it is dynamic and can also group objects.

A single try block can contain multiple catch blocks that

handle different exceptions separately.

C# provides a flexible mechanism called the try-catch statement to

handle exceptions so that a program won't crash when an error occurs.

Objects of a class are stored on the:

heap

Reference types are stored in a part of the memory called the

heap.

Accessor declarations can

include a get accessor, a set accessor, or both.

Prefix

increments the value, and then proceeds with the expression. The prefix example increments the value of x, and then assigns it to y.

After creating the array, you can assign values to individual elements by using the

index number:myArray[0] = 23;

You can also access characters of a string by its

index, just like accessing elements of an array

Like a property, you use get and set accessors for defining an

indexer. However, where properties return or set a specific data member, indexers return or set a particular value from the object instance.

The modulus operator (%) is

informally known as the remainder operator because it returns the remainder of an integer division.

Encapsulation is also called

information hiding.

This statement declares an array of integers. Since arrays are objects, we need to instantiate them with the new keyword:

int[ ] myArray = new int[5]; This instantiates an array named myArray that holds 5 integers.

Our Swap method will work only for

integer parameters. If we want to use it for other types, for example, doubles or strings, we have to overload it for all the types we want to use it with.

Destructors are:

invoked when an object is deleted

void

is a basic data type that defines a valueless state.

The protected access modifier is very similar to private with one difference

it can be accessed in the derived classes. So, a protected member is accessible only from derived classes.

A property can also be private, so

it can be called only from within the class.

The static keyword

it is used to make methods accessible in Main.

A collection typically includes methods to add, remove, and count objects. The for statement and the foreach statement are used to

iterate through collections.

The derived class needs

its base class in order to work, which is why the base class constructor is called first.

A constructor has exactly the same name as

its class, is public, and does not have any return type.

Move()

moves a specified file to a new location

If none of the expressions are in parentheses

multiplicative (multiplication, division, modulus) operators will be evaluated before additive (addition, subtraction) operators. Operators of equal precedence are evaluated from left to right.

It is common to use the capital letter I as the starting letter for an interface

name.

The using keyword states that the program is using a given

namespace.

We can even omit the

new operator: string[ ] names = {"John", "Mary", "Jessica"};

an if can have zero or more else if's and they must come before the last else, which is optional. Once an else if succeeds

none of the remaining else if's or else clause will be tested.

The C# generic collection Dictionary<K, V> class requires all key/value pairs be of the same type K, V. Duplicate keys are

not permitted to ensure that every key/value pair is unique.

The C# generic collection SortedList<K, V> class requires all element key/value pairs to be of the same type K, V. Duplicate keys are

not permitted, which ensures that every key/value pair is unique.

Any accessor of a property can be

omitted.

C# applications run:

on the .NET Framework

How many base classes can one class have?

one

What is the maximum number of base classes a sealed class can have?

one

Briefly, polymorphism is:

one method with different implementations

A static class contains:

only static members

The .NET Framework uses namespaces to

organize its many classes. System is one example of a .NET Framework namespace.

One of the common uses of this is to distinguish class members from

other data, such as local or formal parameters of a method

Constructors can be

overloaded like any method by using different numbers of parameters.

All arithmetic and comparison operators can be

overloaded. For instance, you could define greater than and less than operators for the boxes that would compare the Boxes and return a boolean result. Just keep in mind that when overloading the greater than operator, the less than operator should also be defined.

Now you can call the method in Main and pass in the value for its

parameters (also called arguments): The value 42 is passed to the method as an argument and is assigned to the formal parameter x.

Another common use of this is for

passing the current instance to a method as parameter: ShowPersonInfo(this);

The System.IO namespace has various classes that are used for

performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file, and more.

All methods automatically close the file after

performing the operation.

To access individual array elements

place the element's index number in square brackets

The increment operator has two forms

prefix and postfix.

Collection classes are organized into namespaces and contain built in methods for

processing elements within the collection.

C# supports the following access modifiers:

public, private, protected, internal, protected internal.

Replace(oldValue, newValue)

replaces the specified value in the string.

Bit arrays compactly store bits. Most commonly, they are used to

represent a simple group of boolean flags or an ordered sequence of boolean values.

Math.Abs()

returns the absolute value of its argument.

Math.Cos()

returns the cosine of the specified angle.

IndexOf(value)

returns the index of the first occurrence of the value within the string.

Math.Max()

returns the larger of its two arguments.

Length

returns the length of the string.

Math.Min()

returns the smaller of its two arguments.

Math.Sqrt()

returns the square root of a specified number.

Contains(value)

returns true if the string contains the specified value.

Inheritance allows the derived class to reuse the code in the base class without having to

rewrite it. And the derived class can be customized by adding more members. In this manner, the derived class extends the functionality of the base class.

Math.Round()

rounds the decimal number to its nearest integral value.

A method call with multiple parameters must

separate arguments with commas.

If you have multiple parameters, remember to

separate them with commas, both when declaring them and when calling the method.

You can have as many parameters as needed for a method by

separating them with commas in the definition.

Skipping which accessor creates a read-only property?

set

value is a special keyword, which represents the value we assign to a property using the

set accessor.

Constructors can be very useful for

setting initial values for certain member variables.

We can initialize multidimensional arrays in the same way as

single-dimensional arrays.

C# does not support multiple inheritance,

so you cannot inherit from multiple classes.

A stack is

sometimes called a Last In First Out (LIFO) data structure.

To declare an array, specify its element types with

square brackets int[ ] myArray;

To be able to directly call a method in Main, it should be:

static

Constant members are

static by definition.

Static methods can access only

static members.

Arrays use integer indexes, but indexers can use any type of index, such as

strings, characters, etc.

All standard C# types (int, double, bool, char, etc.) are actually

structs.

Output parameters are similar to reference parameters, except

that they transfer data out of the method rather than accept data in.

default parameter values can be used for calling the same method in different situations without requiring arguments for every parameter.

that you must have the parameters with default values at the end of the parameter list when defining the method.

The class whose properties are inherited by another class is called

the Base class

The class which inherits the properties is called

the Derived class.

The Array class in C# provides various properties and methods to work with arrays. For example

the Length and Rank properties

So what will happen when we create an object of the derived class?

the base class constructor is called first and the derived class constructor is called next. When the object is destroyed, the derived class destructor is invoked and then the base class destructor is invoked.

Because of their global nature, static members can be accessed directly using

the class name without an object.

When calling a generic method, we need to specify the type it will work with by using brackets. So, when Swap<int> is called, the T type is replaced by int. For Swap<string>, T is replaced by string. If you omit specifying the type when calling a generic method,

the compiler will use the type based on the arguments passed to the method.

Math.PI

the constant PI.

Collections provide a more flexible way to work with groups of objects. Unlike arrays,

the group of objects you work with can grow and shrink dynamically as the needs of the application change.

Part of the meaning of the word encapsulation is

the idea of "surrounding" an entity, not just to keep what's inside together, but also to protect it. it also means restricting access to the inner workings of that class.

The factorial method calls itself, and then continues to do so, until the argument equals 1. The exit condition prevents

the method from calling itself indefinitely.

the Length and Rank properties return

the number of elements and the number of dimensions of the array, respectively.

Methods return values using

the return statement.

Generics allow

the reuse of code across different types. For example, let's declare a method that swaps the values of its two parameters

An access modifier defines

the scope and visibility of a class member.

Their value is stored in memory in a location called

the stack.

When you instantiate an object, the data for that object is stored on the heap, while its heap memory address is stored on

the stack.

Inserting an element onto a stack is called pushing. Deleting an element from a stack is called popping. Pushing and popping can be performed only at

the top of the stack.

The generic class stores elements in an array. As you can see, the generic type T is used as

the type of the array, the parameter type for the Push method, and the return type for the Pop and Get methods. Now we can create objects of our generic class:

Properties can be used as if they are public data members, but

they actually include special methods called accessors.

You can pass different arguments to the same method as long as

they are of the expected type.

Hash sets are different from other collections because

they are simply a set of values. They do not have index positions and elements cannot be ordered.

Structs cannot contain default constructors (a constructor without parameters), but

they can have constructors that take parameters. In that case the new keyword is used to instantiate a struct object, similar to class objects.

To access a generic collection in your code, you will need to include the statement:

using Systems.Collections.Generic;

If you are expecting another type of value (such as int or double), the entered data must be converted to that type

using the Convert.ToXXX methods

Implicitly typed variables must be initialized with a

value.

readonly fields can be initialized by the constructor constants should be assigned a value when declared

verdadero

If a method does not return any value, you should use the return type:

void

The Console.ReadLine method

waits for user input and then assigns it to the variable.

To summarize, polymorphism is a

way to call the same method for different objects and generate different results based on the object type. This behavior is achieved through virtual methods in the base class.

Polymorphism can be useful in many cases. For example

we could create a game where we would have different Player types with each Player having a separate behavior for the Attack method. In this case, Attack would be a virtual method of the base class Player and each derived class would override it.

Multiple generic parameters can be used

with a single method. For example: Func<T, U> takes two different generic types.

Generic types can also be used with classes. The most common use for generic classes is

with collections of items, where operations such as adding and removing items from the collection are performed in basically the same way regardless of the type of data being stored.

Virtual methods enable you to

work with groups of related objects in a uniform way.

This can be useful, for example, if your class is working with storage or files. The constructor

would initialize and open the files. Then, when the program ends, the destructor would close the files.

One type of collection is called a stack. Items are

"pushed", or added to the collection, and "popped", or removed from the collection.

Destructors have the following attributes:

- A class can only have one destructor. - Destructors cannot be called. They are invoked automatically. - A destructor does not take modifiers or have parameters. - The name of a destructor is exactly the same as the class prefixed with a tilde (~).

An exception can occur for many different reasons. Some examples:

- A user has entered invalid data. - A file that needs to be opened cannot be found. - A network connection has been lost in the middle of communications. - Insufficient memory and other issues related to physical resources.

Abstract classes have the following features:

- An abstract class cannot be instantiated. - An abstract class may contain abstract methods and accessors. - A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

The System.Collections.Generic namespace includes the following generic collections:

- List<T> - Dictionary<TKey, TValue> - SortedList<TKey, TValue> - Stack<T> - Queue<T> - Hashset<T>

Each method declaration includes:

- the return type - the method name - an optional list of parameters

By default, the first enumerator has the value

0, and the value of each successive enumerator is increased by 1.

Array indexing starts from

0.

Remember that the first element has index

0.

The third element of an array has index:

2

How many elements can the following array store? int[ , , ] array = new int[4, 5, 3];

60

BitArray

A bit array is a collection of bits. The value of a bit can be either 0 (off/false) or 1 (on/true).

sealed

A class can prevent other classes from inheriting it, or any of its members, by using the sealed modifier

Dictionary<U, V>

A dictionary is a collection of unique key/value pairs where a key is used to access the corresponding value. Dictionaries are used in database indexing, cache implementations, and so on.

The for Loop

A for loop executes a set of statements a specific number of times

HashSet<T>

A hash set is a set of unique values where duplicates are not allowed.

List<T>

A list is similar to an array, but the elements in a list can be inserted and removed dynamically. The C# generic collection List<T> class requires all elements be of the same type T.

What is a Method?

A method is a group of statements that perform a particular task. In addition to the C# built-in methods, you may also define your own.

Count

A property that gets the number of elements contained in the list.

Capacity

A property that gets the number of elements the list can hold before needing to be resized.

while

A while loop repeatedly executes a block of code as long as a given condition is true.

How many loops can you nest within each other?

Any

bool

Boolean that can have only one of two values: True or False.

ToArray()

Copies the elements of the list into a new array.

BitArray properties include:

Count - Gets the number of bits in the bit array. IsReadOnly - Gets a value indicating if the bit array is read only or not.

And methods include:

Dequeue() - Returns the object at the beginning of the queue and also removes it. Enqueue(T t) - Adds the object t to the end of the queue.

Deleting an element from a queue is referred to as

Dequeue.

static classes dont

Dont have instances. You cannot instantiate an object of a static class, as only one instance of the static class can exist in a program.

Inserting an element into a queue is referred to as

Enqueue.

A sealed class can be marked as abstract.tf

False

The following exception types are some of the most commonly used:

FileNotFoundException, FormatException, IndexOutOfRangeException, InvalidOperationException, OutOfMemoryException.

There are three major differences between readonly and const fields. If we try to modify the name field anywhere else, we will get an error.

First, a constant field must be initialized when it is declared, whereas a readonly field can be declared without initialization Second, a readonly field value can be changed in a constructor, but a constant value cannot. Third, the readonly field can be assigned a value that is a result of a calculation, but constants cannot

Besides a lot of code repetition, it becomes harder to manage the code because changes in one method mean changes to all of the overloaded methods.

Generics provide a flexible mechanism to define a generic type.

Keys

Gets a sorted and indexed collection containing only the keys in the sorted list.

break

If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Inheritance

Inheritance allows us to define a class based on another class. This makes creating and maintaining an application easy.

Insert(int i, T t)

Inserts an element t at a specific index i in the list.

InsertRange(int i, IEnumerable coll)

Inserts the elements of a collection coll at a specified index i in the list. IEnumerable is the collections interface that supports simple iteration over the collection.

A good example of this is the Math class.

It contains various useful properties and methods for mathematical operations. For example, the Pow method raises a number to a power

Can a single class inherit from multiple abstract classes?

No

The data type of the variable in the foreach loop should match the type of the array elements.

Often the keyword var is used as the type of the variable, as in: foreach (var k in a). The compiler determines the appropriate type for var.

Stack<T> methods include:

Peek() - Returns the element at the top of the stack without removing it. Pop() - Returns the element at the top of the stack and removes it from the stack. Push(T t) - Inserts an element t at the top of the stack.

Which keyword makes class members accessible to only its derived class members?

Protected

Types are used for storing objects.

Reference types

RemoveRange(int i, int count)

Removes a specified number of elements count from the list starting at a specified index i.

Clear()

Removes all the elements from the list.

IndexOfKey(K key)

Returns the index of the specified key within the sorted list.

IndexOfValue(V value)

Returns the index of the specified value within the sorted list.

When you declare a string variable, you basically instantiate an object of type

String.

Which namespace contains the generic collection classes?

System .Collections .Generic

o use the File class you need to use the

System.IO namespace: using System.IO;

Math.Sin()

Taking the sine of a number (number is in radians) returns the sine of the specified angle.

Assume the Employee class inherits the members of the Person class. What is the Person class called?

The Base class

continue

The continue statement is similar to the break statement, but instead of terminating the loop entirely, it skips the current iteration of the loop and continues with the next iteration.

The default Case

The default code executes when none of the cases matches the switch expression.

do-while vs. while

The do-while loop executes the statements at least once, and then tests the condition. The while loop executes the statement only after testing condition.

provides a shorter and easier way of accessing array elements.

The foreach loop

The this Keyword

The this keyword is used inside the class and refers to the current instance of the class, meaning it refers to the current object.

Polymorphism

The word polymorphism means "having many forms". Typically, polymorphism occurs when there is a hierarchy of classes and they are related through inheritance from a common base class.

In some situations there is no meaningful need for the virtual method to have a separate definition in the base class.

These methods are defined using the abstract keyword and specify that the derived classes must define that method on their own.

int is a Struct.

True

Here are additional SortedList<K, V> properties and methods:

Values - Gets a sorted and indexed collection of the values in the sorted list. Clear() - Removes all the elements from the sorted list. ContainsKey(K key) - Returns true when the specified key is present in the sorted list. ContainsValue(V value) - Returns true when a specified value is present in the sorted list. IndexOfKey(K key) - Returns the index of the specified key within the sorted list. IndexOfValue(V value) - Returns the index of the specified value within the sorted list.

Here are the additional Dictionary<K, V> properties and methods:

Values - Gets an indexed collection containing only the values in the dictionary. Clear() - Removes all the key/value pairs from the dictionary. ContainsKey(K key) - Returns true if the specified key is present in the dictionary. ContainsValue(V value) - Returns true if the specified value is present in the dictionary.

When is the constructor called?

When a class object is created

Reading from Files

You can read the content of a file using the ReadAllText method of the File class:

A base class can have multiple derived classes. For example

a Cat class can inherit from Animal.

Just as in real life, objects can contain other objects. For example

a car, which has its own attributes (color, brand, etc.) contains a motor, which as a separate object, has its own attributes (volume, horsepower, etc.). Here, the Car class can have a nested Motor class as one of its members.

In programming, the term type is used to refer to

a class name: We're creating an object of a particular type. Once we've written the class, we can create objects based on that class.

The WriteAllText() method creates

a file with the specified path and writes the content to it. If the file already exists, it is overwritten.

The readonly modifier prevents

a member of a class from being modified after construction.

A property is

a member that provides a flexible mechanism to read, write, or compute the value of a private field.

every C# console application must contain

a method (a function) named Main.

An exception is

a problem that occurs during program execution. Exceptions cause abnormal termination of the program.

The new operator instantiates an object and returns

a reference to its location

string

a sequence of characters.

A multidimensional array (int[,]) is

a single block of memory (essentially a matrix). It always has the same amount of columns for every row.

char

a single character.

A class constructor is

a special member method of a class that is executed whenever a new object of that class is created.

A struct type is

a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory.

Class B inherits from class A. The constructor of class A displays "a", while the class B constructor displays "b". What is output to the screen when the code A a = new B(); is run?

ab

abstract method declarations are only permitted in

abstract classes.

An abstract class can have multiple

abstract members.

You cannot create objects of a class containing an abstract method, which is why the class itself should be

abstract.

Notice the dot operator (.) that is used to

access and call the method of the object.

Also, all members of an interface are always public, and no

access modifiers can be applied to them.

Encapsulation is implemented by using

access modifiers.

We can also use the exception object e to

access the exception details, such as the original error message (e.Message):

A member that has been defined public can be

accessed from outside the class, as long as it's anywhere within the scope of the class object.

As you can see, we access the property ONE using the name of the class, just like a static member. This is because

all const members are static by default.

A derived class inherits

all the members of the base class, including its methods.

A jagged array is

an array whose elements are arrays.

for (; ;) {} is

an infinite loop.

A jagged array is an array-of-arrays, so

an int[ ][ ] is an array of int[ ], each of which can be of different lengths and occupy their own block in memory.

he override keyword is not needed when you implement an

an interface.

A collection can grow and shrink to accommodate

any number of objects.

Public members may be accessed from

anywhere outside of the class

when we declare an object of class Clients, we use an index to refer to specific objects like the elements of an

array:

Indexes in strings are similar to

arrays, they start from 0.

The set accessor is used to

assign a value to variable;

Arrays can have any number of dimensions

but keep in mind that arrays with more than three dimensions are harder to manage.

C# has two ways of storing data:

by reference and by value.

Non-Generic Collections

can store items that are of type Object. Since an Object data type can refer to any data type, you run the risk of unexpected outcomes. Non-generic collections may also be slower to access as well as execute.

The Console class is also an example of a static

class. We use its static WriteLine() method to output to the screen, or the static ReadLine() method to get user input. The Convert class used to convert value types is also a static class.

Members marked as abstract, or included in an abstract class, must be implemented by

classes that derive from the abstract class.

Destructors can be very useful for releasing resources before coming out of the program. This can include

closing files, releasing memory, and so on.

The name of the property can be anything you want, but

coding conventions dictate properties have the same name as the private field with a capital letter.

Static classes are useful for

combining logical properties and methods.

To implement multiple interfaces, use a

comma separated list of interfaces when creating the class: class A: IShape, IAnimal, etc.

An interface is a completely abstract class, which

contains only abstract members. It is declared using the interface keyword

Operator overloading means:

defining custom actions for operators

Delete()

deletes the specified file.

The term implementing an interface is used (opposed to the term "inheriting from") to

describe the process of creating a class based on an interface.

Exists()

determines whether the specified file exists.

Different kinds of collections are suited to

different kinds of applications, and some are highly specialized to specific tasks. For example, Dictionaries are used to represent connections on social websites (such as Twitter, Facebook), queues can be used to create task schedulers, HashSets are used in searching algorithms, etc.

An array can have multiple

dimensions

double

double-precision version of float.

Heap is used for

dynamic memory allocation, which includes custom objects, that might need additional memory during the runtime of your program.

Auto-Implemented Properties

enable you to quickly specify a property of a class without having to write code to Get and Set the property

You must access static members using the class name. If you try to access them via an object of that class, you will generate an

error.

Interfaces can contain properties, methods, etc. but cannot contain

fields (variables).

When a class implements an interface, it must also

implement, or define, all of its methods.

Variables declared using the var keyword are called

implicitly typed variables.

Structs do not support

inheritance and cannot contain virtual methods.

you can use interfaces to implement multiple

inheritance.

Insert(index, value)

inserts the value into the string starting from the specified index.

An object is called an

instance of a class.

Since a collection is a class you must first declare an

instance of the class before you can add elements to that collection.

The process of creating objects is called:

instantiation

Creating an object is called

instantiation.

int

integer

Access modifiers are

keywords used to specify the accessibility of a member.

Declaring your own namespaces can help you group your class and method names in

larger programming projects.

You typically use an indexer if the class represents a

list, collection, or array of objects.

The private access modifier

makes members accessible only from within the class and hides them from the outside.

the public access modifier

makes the member accessible from the outside of the class.

Enums define variables that represent

members of a fixed set. Some sample Enum uses include month names, days of the week, cards in a deck, etc.

You can include an access modifier for fields and methods (also called

members) of a class.

The virtual keyword allows

methods to be overridden in derived classes.

Structs can contain

methods, properties, indexers, and so on

A default constructor has

no parameters

C# includes the HashSet<T> class in the generic collections namespace. All HashSet<T> elements are required to be

of the same type T.

If no access modifier is defined, the member is

private by default.

You can also designate class members as

private or protected.

Which of the following determines the current state of an object?

properties

The characteristics of an object are called

properties.

To make a member of a class accessible from outside the class declaration, you should declare it as:

public

When you do not need any custom logic, C# provides a fast and effective mechanism for declaring private members through their properties. to create a private member that can only be accessed through the Name property's get and set accessors, use the following syntax:

public string Name { get; set; } Name is called an auto-implemented property.

Because non-generic collections are error prone and less performant, it is

recommended to always use generic collections from the System.Collections.Generic namespace if available and to avoid using legacy collections from the System.Collections namespace.

An array is a:

reference type

Remove(index)

removes all characters in the string after the specified index.

Math.E

represents the natural logarithmic base e.

get is used to

return its value.

Output parameters are particularly useful when you need to

return multiple values from a method. the out keyword is used both when defining the method and when calling it.

DateTime.DaysInMonth()

return the number of days in the specified month

Math.Pow()

returns a specified number raised to the specified power.

Substring(index, length)

returns a substring of the specified length, starting from the specified index. If length is not specified, the operation continues to the end of the string.

Stack is used for

static memory allocation, which includes all your value types, like x.

The Main method is static, as it is the starting point of any program. Therefore any method called directly from Main had to be

static.

For example, BitArrays can be used in image processing to

store the individual bits of a gray-scale image.

The Console.ReadLine() method returns a

string value.

Enums are often used with

switch statements.

Polymorphism means

that a call to a member method will cause a different implementation to be executed depending on the type of object that invokes the method.

Simply, polymorphism means

that a single method can have a number of different implementations.

The sealed keyword provides a level of protection to your class so

that other classes cannot inherit from it.

By value copies the argument's value into the method's formal parameter.

the Sqr method does not change the original value of the variable, as it is passed by value, meaning that it operates on the value, not the actual variable. In this case, x is the parameter of the Sqr method and a is the actual argument passed into the method. By default, C# uses call by value to pass arguments.

All members of the interface are by default abstract, so no need to use the

the abstract keyword.

We can omit the size declaration when the number of elements are provided in

the curly braces:string[ ] names = new string[ ] {"John", "Mary", "Jessica"};

We can also use the generic class with custom types, such as

the custom defined Person type.

we can access and modify the Name property of the base class from

the derived class.But, if we try to access it from outside code, we will get an error:

The virtual Draw method in the Shape base class can be overridden in

the derived classes. In this case, Circle and Rectangle have their own Draw methods. Now, we can create separate Shape objects for each derived type and then call their Draw methods:

The accessor of a property contains

the executable statements that help in getting (reading or computing) or setting (writing) a corresponding field.

Arrays in C# are zero-indexed meaning

the first member has index 0, the second has index 1, and so on.

you can declare an array of 10 integers and assign each element an even value with

the following loop:int[ ] a = new int[10]; for (int k = 0; k < 10; k++) { a[k] = k*2; }

In a generic class we do not need to define the generic type for its methods, because

the generic type is already defined on the class level.

A nested class acts as a member of the class, so it can have

the same access modifiers as other members (public, private, protected).

The enum keyword is used

to declare an enumeration: a type that consists of a set of named constants called the enumerator list.

As you can see, each object invoked its own Draw method, thanks to

to polymorphism.

Declaration of an indexer is

to some extent similar to a property. The difference is that indexer accessors require an index.

access to private members is limited

to their class.

The polymorphic approach allows us to

treat each object the same way. As all objects are of type Shape, it is easier to maintain and work with them. You could, for example, have a list (or array) of objects of that type and work with them dynamically, without knowing the actual derived type of each object.

Similar to any other method, an overloaded operator has a return

type and a parameter list.

To declare a constant

use the const modifier. Constants must be initialized with a value when declared.

Named arguments

use the name of the parameter followed by a colon and the value.

A collection organizes related data in a computer so that it can be

used efficiently.

exceptions are caused by

user error, programmer error, or physical resource issues. However, a well-written program should handle all possible exceptions.

Constants store a

value that cannot be changed from their initial assignment.

Method overloading is

when multiple methods have the same name, but different parameters.

The finally block can be used, for example,

when you work with files or other resources. These should be closed or released in the finally block, whether an exception is raised or not.

Queues are used

whenever we need to manage objects in order starting with the first one in. Scenarios include printing documents on a printer, call center systems answering people on hold people, and so on.

Overloaded operators are methods with special names,

where the keyword operator is followed by the symbol for the operator being defined.

Parameters are optional; that is

you can have a method with no parameters.

polymorphism is used when

you have different derived classes with the same method, which has different implementations in each class. This behavior is achieved through virtual methods that are overridden in the derived classes.

To execute a method

you simply call the method by using the name and any required arguments in a statement.

variable placeholders

{3}

Array values should be provided in a comma separated list enclosed in

{curly braces}.


Conjuntos de estudio relacionados

Theology - Chapter 7 - Resurrection and Ascension of Jesus Christ

View Set

Chapter 17: Government and Politics

View Set

Biology: Fall 2015 Final Exam (15-19) FI

View Set