Csharp_midterm

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Conditional Operators

&& || !

C# Parameter Modifiers

*(None) If a parameter is not marked with a parameter modifier, it is assumed to be passed by value, meaning the called method receives a copy of the original data. *out Output parameters must be assigned by the method being called and, therefore, are passed by reference. If the called method fails to assign output parameters, you are issued a compiler error. *ref The value is initially assigned by the caller and may be optionally modified by the called method (as the data is also passed by reference). No compiler error is generated if the called method fails to assign a ref parameter. *params This parameter modifier allows you to send in a variable number of arguments as a single logical parameter. A method can have only a single params modifier, and it must be the final parameter of the method. In reality, you might not need to use the params modifier all too often; however, be aware that numerous methods within the base class libraries do make use of this C# language feature.

C# Access Modifiers

+++public++++ Types or type members Public items have no access restrictions. A public member can be accessed from an object, as well as any derived class. A public type can be accessed from other external assemblies. ++++private++++ Type members or nested types Private items can be accessed only by the class (or structure) that defines the item. ++++protected++++ Type members or nested types Protected items can be used by the class that defines it and any child class. However, protected items cannot be accessed from the outside world using the C# dot operator. ++++ internal++++ Types or type members Internal items are accessible only within the current assembly. Therefore, if you define a set of internal types within a .NET class library, other assemblies are not able to use them. ++++protected internal ++++ Type members or nested types When the protected and internal keywords are combined on an item, the item is accessible within the defining assembly, within the defining class, and by derived classes.

The 'abstract' keyword in C# can be used on which of the following?

A class A virtual method on a abstract class An automatic property

Useful Types of System.Collections

ArrayList BitArray Hashtable Queue SortedList Stack

.NET Numerical Format Characters

C or c Used to format currency. By default, the flag will prefix the local cultural symbol (a dollar sign [$] for U.S. English). D or d Used to format decimal numbers. This flag may also specify the minimum number of digits used to pad the value. E or e Used for exponential notation. Casing controls whether the exponential constant is uppercase (E) or lowercase (e). F or f Used for fixed-point formatting. This flag may also specify the minimum number of digits used to pad the value. G or g Stands for general. This character can be used to format a number to fixed or exponential format. N or n Used for basic numerical formatting (with commas). X or x Used for hexadecimal formatting. If you use an uppercase X, your hex format will also contain uppercase characters.

Building Blocks of the .NET Platform

CLR, CTS, and CLS

Members of System.Array

Clear() This static method sets a range of elements in the array to empty values (0 for numbers, null for object references, false for Booleans). CopyTo() This method is used to copy elements from the source array into the destination array. Length This property returns the number of items within the array. Rank This property returns the number of dimensions of the current array. Reverse() This static method reverses the contents of a one-dimensional array. Sort() This static method sorts a one-dimensional array of intrinsic types. If the elements in the array implement the IComparer interface, you can also sort your custom types

.NET equivalent of a type-safe, C-style function pointer.

Delegates

Members of the Queue<T> Type

Dequeue() Removes and returns the object at the beginning of the Queue<T> Enqueue() Adds an object to the end of the Queue<T> Peek() Returns the object at the beginning of the Queue<T> without removing it

Classes of System.Collections.Generic

Dictionary<TKey, TValue> LinkedList<T> List<T> Queue<T> SortedDictionary<TKey,TValue> SortedSet<T> Stack<T>

Another handy generic collection is the XXX<TKey,TValue> type, which allows you to hold any number of objects that may be referred to via a unique key.

Dictionary<TKey, TValue> Class

It is good practice to throw an exception on both out of memory errors AND invalid user input.

False

The MemberwiseClone method is defined on the ICloneable interface.

False

named collection of abstract member definitions, which may be supported (i.e., implemented) by a given class or structure.

Interfaces

Key Benefits of the .NET Platform

Interoperability with existing code Support for numerous programming languages A common runtime engine shared by all .NET-aware languages Language integration A comprehensive base class library: A simplified deployment model:

Members of System.String

Length This property returns the length of the current string. Compare() This static method compares two strings. Contains() This method determines whether a string contains a specific substring. Equals() This method tests whether two string objects contain identical character data. Format() This static method formats a string using other primitives (e.g., numerical data, other strings) and the {0} notation examined earlier in this chapter. Insert() This method inserts a string within a given string. PadLeft() These methods are used to pad a string with some characters. PadRight() Remove() These methods are used to receive a copy of a string with modifications (characters removed or replaced). Replace() Split() This method returns a String array containing the substrings in this instance that are delimited by elements of a specified char array or string array. Trim() This method removes all occurrences of a set of specified characters from the beginning and end of the current string. ToUpper() These methods create a copy of the current string in uppercase or lowercase format, respectively. ToLower()

When you create an instance of a generic class or structure, you specify the type parameter when you declare the variable and when you invoke the constructor

List<Person> morePeople = new List<Person>();

Given the code snippet below, what is NOT a valid call to the Log method? enum LogLevel {Info, Warning, Error} static void Log{string message, LogLevel level=LogLevel.Info, string owner ="System") {Console.WriteLine("{0} {1}: {2}", owner, level, message); }

Log(message: "Terminating", level: LogLevel.Error, "Programmer");

Which of the following are NOT core features found in all versions of the C# language?

Named method arguments Optional method parameters Generics String interpolation

core C# features that are found in all versions of the language:

No pointers required! Automatic memory management through garbage collection. Formal syntactic constructs for classes, interfaces, structures, enumerations, and delegates. The C++-like ability to overload operators for a custom type, without the complexity Support for attribute-based programming. The ability to build generic types and generic members. Support for anonymous methods, which allow you to supply an inline function anywhere a delegate type is required The ability to define a single type across multiple code files (or if necessary, as an in- memory representation) using the partial keyword Support for strongly typed queries (e.g., LINQ) used to interact with various forms of data Support for anonymous types that allow you to model the structure of a type (rather than its behavior) on the fly in code. The ability to extend the functionality of an existing type (without subclassing) using extension methods. Inclusion of a lambda operator (=>), which even further simplifies working with .NET delegate types. A new object initialization syntax, which allows you to set property values at the time of object creation. Support for optional method parameters, as well as named method arguments. Support for dynamic lookup of members at runtime via the dynamic keyword. Working with generic types is much more intuitive, given that you can easily map generic data to and from general System.Object collections via covariance and contravariance.

What are the possible ways to use the 'sealed' keyword in C#?

On a class On a virtual method On a property

True

One of the key advantages of the .NET runtime over other runtimes (like Java's JVM) is that the .NET runtime provides a single, well-defined runtime layer that is shared by all .NET-aware languages (e.g., Visual Basic, C#, F#, etc.).

What can be written generically;

Only classes, structures, interfaces, and delegates. enum types cannot.

Having the GiveBonus virtual method respond differently depending on the class is a great example of which of the following?

Polymorphism

The three pillars of object-oriented programming are:

Polymorphism Inheritance Encapsulation

XXXX are containers that ensure items are accessed in a first-in, first-out manner.

Queue<T> Class

The XXX<T> class is useful because it automatically ensures that the items in the set are sorted when you insert or remove items. However, you do need to inform the XXX<T> class exactly how you want it to sort the objects, by passing in as a constructor argument an object that implements the generic IComparer<T> interface.

SortedSet<T> Class

The XXXX<T> class represents a collection that maintains items using a last-in, first-out manner.

Stack<T>. Stack<T> defines members named Push() and Pop() to place items onto or remove items from the stack.

.NET namespace that contains nongeneric collection classes.

System.Collections System.Collections.Specialized

check for 'system.console.Writeline();' in the body of function

The following code will generate a compile time error because it is missing a 'using System;' line at the top.

$36.00, 00047, 58.00, 69.00

The following line of code produces which output? Console.WriteLine("{1:c}, {2:d5}, {3:n}, {4:f2}", 25, 36, 47, 58, 69);

Static constructors allow one to initialize static data members once at run time rather than at compile time.

True

Strings Are Immutable. One of the interesting aspects of System.String is that after you assign a string object with its initial value, the character data cannot be changed.

True

Structure types are well suited for modeling mathematical, geometrical, and other "atomic" entities in your application. A structure (such as an enumeration) is a user-defined type; however, structures are not simply a collection of name-value pairs. Rather, structures are types that can contain any number of data fields and members that operate on these fields.

True

The 'base' keyword can be used to invoke both base class constructors as well as base class methods.

True

The advantage of using data encapsulation comes when the implementation of the class changes but the interface remains the same.

True

The first pillar of OOP is called encapsulation. This trait boils down to the language's ability to hide unnecessary implementation details from the object user.

True

The following code catch block will compile successfully: catch(ApplicationException ae) {Console.WriteLine("Application error{0}, ae); catch(SystemException se) { Console.WriteLine("System error {0}", se); }

True

When using the 'override' keyword on a virtual method, you must use the same parameter passing mechanism (i.e., ref, out, params) as well as the same type for every method parameter.

True

abstract method is a member in a base class that does not provide a default implementation but does provide a signature.

True

array is a set of data items, accessed using a numerical index.

True

implicit typing applies only to local variables in a method or property scope. It is illegal to use the var keyword to define return values, parameters, or field data of a custom type

True

inheritance, boils down to the language's ability to allow you to build new class definitions based on existing class definitions. In essence, inheritance allows you to extend the behavior of a base (or parent) class by inheriting core functionality into the derived subclass (also called a child class).

True

local variables declared with the var keyword must be assigned an initial value at the exact time of declaration and cannot be assigned the initial value of null.

True

polymorphism. This trait captures a language's ability to treat related objects in a similar manner. Specifically, this tenant of an object-oriented language allows a base class to define a set of members (formally termed the polymorphic interface) that are available to all descendants. A class's polymorphic interface is constructed using any number of virtual or abstract members

True

utility class is a class that does not maintain any object-level state and is not created with the new keyword. Rather, a utility class exposes all functionality as class-level (aka static) members.

True

What output does the following program produce? string s1="Hello"; string s2="Hello"; char[] a1={'a','b','c'}; char[] a2={'a','b','c'}; Console.Writeline("{0},{1}", s1==s2, a1==a2);

True, False

The 'yield return' syntax can be used to provide multiple "named iterator" methods.

Ture

1)No direct pointer manipulation required (although possible) 2)Automatic memory management 3)Overload operators on a custom type

Which of the following are core features found in all versions of the C# language?

1)Assembly manifest 2)Type metadata 3)CIL

Which of the following are found in a .NET assembly?

1)static int Main(string[] args); 2)static int Main(); 3)static void Main();

Which of the following is a valid Main signature for an entry point of a C# console application?

static int Main(int args);

Which of the following is not a valid Main signature for an entry point of a C# console application?

Which of the following are good reasons to define an Interface rather than an Abstract class?

You want to specify the behavior of a particular data type, but you are not concerned about who implements its behavior You expect that unrelated classes would implement a common protocol You want to take advantage of multiple inheritance

String Literal Escape Characters

\' Inserts a single quote into a string literal. \" Inserts a double quote into a string literal. \\ Inserts a backslash into a string literal. This can be quite helpful when defining file or network paths. \a Triggers a system alert (beep). For console programs, this can be an audio clue to the user. \n Inserts a new line (on Windows platforms). \r Inserts a carriage return. \t Inserts a horizontal tab into the string literal.

The following code produces which output? string s1="abc"; int[] a1={1,2,3}; s1.ToUpper(); System.Array.Reverse(a1); Console.WriteLine("{0}, |{1},{2},{3}|", s1, a1[0], a1[1], a1[2]);

abc, [3, 2, 1]

The Intrinsic Data Types of C#

bool Yes System.Boolean true or false sbyte No System.S Byte -128 to 127 Signed 8-bit number byte Yes System.Byte 0 to 255 Unsigned 8-bit number short Yes System.Int16 -32,768 to 32,767 Signed 16-bit number ushort No System.UInt16 0 to 65,535 Unsigned 16-bit number int Yes System.Int32 -2,147,483,648 to 2,147,483,647 Signed 32-bit number uint No System.UInt32 0 to 4,294,967,295 Unsigned 32-bit number long Yes System.Int64 -9,223,372,036,854,775, 808 to 9,223,372,036,854,775,807 Signed 64-bit to number ulong No System.UInt64 0 to 18,446,744,073,709,551,615 Unsigned 64-bit number char Yes System.Char U+0000 to U+ffff Single 16-bit Unicode character float Yes System.Single -3.4 10 38 to +3.4 10 38 32-bit floating-point number double Yes System.Double ±5.0 10 -324 to ±1.7 10 308 64-bit floating-point number decimal Yes System.Decimal (-7.9 x 10 28 to 7.9 x 10 28 )/(10 0 to 28 ) 128-bit signed number string Yes System.String Limited by system memory Represents a set of Unicode characters Object Yes System.Object Can store any data type in an object variable The base class of all typ

mechanism to store the data in a value type within a reference variable.

boxing

allows you to specify placeholders (type parameters) that you specify at the time of object creation (or invocation, in the case of generic methods).

generic item

Which lines of code does produce a compile time error?

int myInt = null; bool myBool = null; double myDouble = null;

reference type

is an object allocated on the garbage-collected managed heap.

The relevant C# keywords that support polymorphism are:

override virtual abstract

The relevant C# keywords that support data encapsulation are:

private protected

Which lines of code do NOT produce a compile time error?

string myString = null; int[] myInt = null;

the process of converting the value held in the object reference back into a corresponding value type on the stack.

unboxing

Ccode that cannot be directly hosted by the .NET runtime is termed

unmanaged code.

the .NET platform allows you to use the XXX keyword to get extremely specific about what a given type parameter must look like. Using this keyword, you can add a set of constraints to a given type parameter, which the C# compiler will check at compile time.

where

The type parameter <T> must be derived from the class specified by NameOfBaseClass.

where T : NameOfBaseClass

The type parameter <T> must implement the interface specified by NameOfInterface. You can separate multiple interfaces as a commadelimited list.

where T : NameOfInterface

The type parameter <T> must not have System.ValueType in its chain of inheritance (i.e., <T> must be a reference type).

where T : class

The type parameter <T> must have a default constructor. This is helpful if your generic type must create an instance of the type parameter because you cannot assume you know the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type.

where T : new()

The type parameter <T> must have System.ValueType in its chain of inheritance (i.e., <T> must be a structure).

where T : struct

C# defines two simple constructs to alter the flow of your program, based on various contingencies.

• The if/else statement • The switch statement

the flow of constructor logic is as follows:

• You create your object by invoking the constructor requiring a single int. • This constructor forwards the supplied data to the master constructor and provides any additional startup arguments not specified by the caller. • The master constructor assigns the incoming data to the object's field data. • Control is returned to the constructor originally called and executes any remaining code statements.

the variable default value

• bool variables are set to false. • Numeric data is set to 0 (or 0.0 in the case of floating-point data types). • char variables are set to a single empty character. • BigInteger variables are set to 0. • DateTime variables are set to 1/1/0001 12:00:00 AM. • Object references (including strings) are set to null.

C# provides the following four iteration constructs:

• for loop • foreach/in loop • while loop • do/while loop

handy programming construct that allow you to group name-value pairs

Enumerations

A class can be both sealed and abstract.

False

short list of the benefits generic containers provide over their nongeneric counterparts:

Generics provide better performance because they do not result in boxing or unboxing penalties when storing value types. Generics are type safe because they can contain only the type of type you specify. Generics greatly reduce the need to build custom collection types because you specify the "type of type" when creating the generic container.

Useful Classes of System.Collections.Specialized

HybridDictionary ListDictionary StringCollection BitVector32

Key Interfaces Supported by Classes of System.Collections.Generic

ICollection<T> IComparer<T> IDictionary<TKey, TValue> IEnumerable<T> IEnumerator<T> IList<T> ISet<T>

One of the main differences between abstract classes and interfaces is that abstract classes can include implementations whereas Interfaces cannot.

True

Another use of the this keyword is to design a class using a technique termed constructor chaining.

True

Automatic properties reduce the amount of typing by eliminating the need to define a private backing field.

True

C# class may define any number of static members, which are declared using the static keyword. When you do so, the member in question must be invoked directly from the class level, rather than from an object reference variable.

True

C# language does provide for implicitly typing of local variables using the var keyword. The var keyword can be used in place of specifying a specific data type (such as int, bool, or string).

True

C# supplies a this keyword that provides access to the current class instance. One possible use of the this keyword is to resolve scope ambiguity, which can arise when an incoming parameter is named identically to a data field of the class.

True

Encapsulation provides a way to preserve the integrity of an object's state data. Rather than defining public fields (which can easily foster data corruption), you should get in the habit of defining private data, which is indirectly manipulated using one of two main techniques. • You can define a pair of public accessor (get) and mutator (set) methods. • You can define a public .NET property.

True

Every C# class is provided with a "freebie" default constructor that you can redefine if need be.

True

Like other modern object-oriented languages, C# allows a method to be overloaded. Simply put, when you define a set of identically named methods that differ by the number (or type) of parameters, the method in question is said to be overloaded.

True


Ensembles d'études connexes

Chapter 7. Communicating in Social and Professional Relationships

View Set

Ch. 13: The Nekton-Swimmers of the Sea

View Set

Chapter 16 review Spanish American Revolutions

View Set

Management/Strategy Exam 1 (I-Core)

View Set

Pharmacology - Prep U - Chapter 23

View Set