C#/.NET/MVC/Core

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

static keyword

A 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.

Property

A C# property is composed by defining a get scope (accessor) and a set scope (mutator) directly within the property itself. Notice that the property specifies the type of data it is encapsulating by what appears to be a return value. Also take note that, unlike a method, properties do not make use of parentheses. Within a "set" scope of a property, you use a token named value, which is used to represent the incoming value used to assign the property by the caller. This token is not a true C# keyword, but is what is known as a contextual keyword. When the token value is within the set scope of the property, it always represents the value being assigned by the caller, and it will always be the same underlying data type as the property itself. Properties support encapsulation of the member field value, and make the types easier to manipulate in that properties are able to respond to the intrinsic operators of C#.

Common Language Specification (CLS)

A given .NET-aware language might not support each and every feature defined by the CTS. The Common Language Specification, or CLS, is a related specification that defines a subset of common types and programming constructs that all .NET programming languages can agree on. Thus, if you build .NET types that expose only CLS-compliant-features, you can rest assured that all .NET-aware languages can consume them. Conversely, if you make use of a data type or programming construct that is outside of the bounds of the CLS, you cannot guarantee that every .NET programming language can interact with your .NET code library.

Polymorphism

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. A virtual member is a member in a base class that defines a default implementation that may be changed (or more formally speaking, overridden) by a derived class. In contrast, an abstract method is a member in a base class that does not provide a default implementation, but does provide a signature. When a class derives from a base class defining an abstract method, it must be overridden by a derived type. In either case, when derived types override the members defined by a base class, they are essentially redefining how they respond to the same request.

C# nullable types

A nullable type can represent all the values of its underlying type, plus the value null. Thus if we declare a nullable bool, it could be assigned a value from the set {true, false, null}.

Single-Page Applications (SPA)

A web application whose initial content is delivered as a combination of HTML and JavaScript and whose subsequent operations are performed using a RESTful web service that delivers data via JSON in response to Ajax requests. Contrast this with many other MVC apps, where operations performed by the user result in new HTML documents being generated in response to synchronous HTTP requests, which could be referred to as round-trip applications (RTAs). The advantages of a SPA are that less bandwidth is required and that the user receives a smoother experience. The disadvantages are that the smoother experience can be hard to achieve and that the complexity of the JavaScript code required for a SPA demands careful design and testing. Most applications mix and match SPA and RTA techniques, where each major functional area of the application is delivered as a SPA, and navigation between functional areas is managed using standard HTTP requests that create a new HTML document.

Abstract methods and abstract classes

Abstract methods, similar to methods within an interface, are declared without any implementation. They are declared with the purpose of having the child class provide implementation. They must be declared within an abstract class. A class declared abstract may or may not include abstract methods. They are created with the purpose of being a super class. Abstract classes and methods are declared with the 'abstract' keyword. Abstract classes can only be extended, and cannot be directly instantiated. Abstract classes provide a little more than interfaces. Interfaces do not include fields and super class methods that get inherited, whereas abstract classes do. This means that an abstract class is more closely related to a class which extends it, than an interface is to a class that implements it. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. Abstract methods have no implementation, so the method definition is followed by a semicolon instead of a normal method block. Derived classes of the abstract class must implement all abstract methods. When an abstract class inherits a virtual method from a base class, the abstract class can override the virtual method with an abstract method. For example: public abstract override void DoWork(int i); If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method—in the previous example, DoWork on class F cannot call DoWork on class D. In this way, an abstract class can force derived classes to provide new method implementations for virtual methods.

Abstract members of an abstract base class

An abstract base class can define any number of abstract members. Abstract members can be used whenever you wish to define a member that does not supply a default implementation, but must be accounted for by each derived class. By doing so, you enforce a polymorphic interface on each descendent, leaving them to contend with the task of providing the details behind your abstract methods.

Assembly

An assembly is a file that is automatically generated by the compiler upon successful compilation of every .NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. The entire process will run in the background of your application; there is no need for you to learn deeply about assemblies. However, a basic knowledge about this topic will help you to understand the architecture behind a .NET application. An Assembly contains Intermediate Language (IL) code, which is similar to Java byte code. In the .NET language, it consists of metadata. Metadata enumerates the features of every "type" inside the assembly or the binary. In addition to metadata, assemblies also have a special file called Manifest. It contains information about the current version of the assembly and other related information. In .NET, there are two kinds of assemblies, such as Single file and Multi file. A single file assembly contains all the required information (IL, Metadata, and Manifest) in a single package. The majority of assemblies in .NET are made up of single file assemblies. Multi file assemblies are composed of numerous .NET binaries or modules and are generated for larger applications. One of the assemblies will contain a manifest and others will have IL and Metadata instructions. The main benefit of Intermediate Language is its power to integrate with all NET languages. This is because all .NET languages produce the same IL code upon successful compilation; hence, they can interact with each other very easily. However, .NET is not yet declared as a platform-independent language; efforts are on at Microsoft to achieve this objective. As of today, .NET applications are equipped to run only on Windows.

Enums

An enum is a custom data type of name/value pairs. By default, the first element is set tothe value zero (0), followed by an n + 1 progression. You are free to change the initial value as you see fit. For example, if it made sense to number the members of EmpType as 102 through 105, you could do so as follows: enum EmpType { Manager = 102, Grunt, // = 103 Contractor, // = 104 VicePresident }

Interface

An interface contains definitions for a group of related functionalities that a class or a struct can implement. By using interfaces, you can, for example, include behavior from multiple sources in a class. That capability is important in C# because the language doesn't support multiple inheritance of classes. In addition, you must use an interface if you want to simulate inheritance for structs, because they can't actually inherit from another struct or class. Interfaces can contain methods, properties, events, indexers, or any combination of those four member types. An interface can't contain constants, fields, operators, instance constructors, finalizers, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static. To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member. When a class or struct implements an interface, the class or struct must provide an implementation for all of the members that the interface defines. The interface itself provides no functionality that a class or struct can inherit in the way that it can inherit base class functionality. However, if a base class implements an interface, any class that's derived from the base class inherits that implementation.

Interface; Interface Types

An interface is nothing more than a named set of abstract members. Recall from Chapter 6 that abstract methods are pure protocol in that they do not provide a default implementation. The specific members defined by an interface depend on the exact behavior it is modeling. Said another way, an interface expresses a behavior that a given class or structure may choose to support. Furthermore, as you will see in this chapter, a class or structure can support as many interfaces as necessary, thereby supporting (in essence) multiple behaviors. Example: public interface IDbConnection : IDisposable { // Methods IDbTransaction BeginTransaction(); IDbTransaction BeginTransaction(IsolationLevel il); void Close(); // Properties string ConnectionString { get; set; } int ConnectionTimeOut { get; set; } string Database { get; } }

protected keyword

Applies to type members or nested types. Protected items can be used by the class which defines it, and any child class. However, protected items cannot be accessed from the outside world using the C# dot operator.

protected internal keyword

Applies to type members or nested types. When the protected and internal keywords are combined on an item, the item is accessible within the defining assembly, the defining class, and by derived classes.

internal keyword

Applies to 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 make use of them.

The role of C# class types

As far as the .NET platform is concerned, the most fundamental programming construct is the class type. Formally, a class is a user-defined type that is composed of field data (often called member variables) and members that operate on this data (such as constructors, properties, methods, events, and so forth). Collectively, the set of field data represents the "state" of a class instance (otherwise known as an object). The power of object-oriented languages, such as C#, is that by grouping data and related functionality in a unified class definition, you are able to model your software after entities in the real world.

Using the this keyword to channel constructor calls

Aside from directing calls to a given constructor based on the number of arguments passed, you can also use the this keyword to direct the calls based on the content of the parameter/argument passed. For example: // Constructor chaining. public Motorcycle() {} public Motorcycle(int intensity) : this(intensity, "") {} public Motorcycle(string name) : this(0, name) {} // This is the 'master' constructor that does all the real work. public Motorcycle(int intensity, string name) { if (intensity > 10) { intensity = 10; } driverIntensity = intensity; driverName = name; }

optional parameters

C# allows you to create methods that can take optional arguments. This technique allows the caller to invoke a single method while omitting arguments deemed unnecessary, provided the caller is happy with the specified defaults. E.g. static void EnterLogData(string message, string owner = "Programmer")

Const keyword

C# offers the const keyword define constant data, which can never change after the initial assignment. The initial value assigned to the constant must be specified at the time you define the constant.

The C# as keyword

C# provides the as keyword to quickly determine at runtime whether a given type is compatible with another. When you use the as keyword, you are able to determine compatibility by checking against a null return value.

The C# is keyword vs the as keyword

C# provides the as keyword to quickly determine at runtime whether a given type is compatible with another. When you use the as keyword, you are able to determine compatibility by checking against a null return value. Unlike the as keyword, the is keyword returns false, rather than a null reference, if the two types are incompatible.

C# response files

C# response files contain all the instructions to be used during the compilation of your current build. By convention, these files end in a *.rsp (response) extension.

Common Intermediate Language (CIL)

Common Intermediate Language (CIL), formerly called Microsoft Intermediate Language (MSIL), is the lowest-level human-readable programming language defined by the Common Language Infrastructure (CLI) specification and is used by the .NET Framework, .NET Core, and Mono. Languages which target a CLI-compatible runtime environment compile to CIL, which is assembled into an object code that has a bytecode-style format. CIL is an object-oriented assembly language, and is entirely stack-based. Its bytecode is translated into native code or—most commonly—executed by a virtual machine.

Understanding abstract classes

Currently, the Employee base class has been designed to supply various data members for its descendents, as well as supply two virtual methods (GiveBonus() and DisplayStats()) that may be overridden by a given descendent. While this is all well and good, there is a rather odd byproduct of the current design; you can directly create instances of the Employee base class: Employee X = new Employee(); In this this example, the only real purpose of the Employee base class is to define common members for all subclasses. In all likelihood, you did not intend anyone to create a direct instance of this class, reason being that the Employee type itself is too general of a concept. Given that many base classes tend to be rather nebulous entities, a far better design for this example is to prevent the ability to directly create a new Employee object in code. In C#, you can enforce this programmatically by using the abstract keyword in the class definition, thus creating an abstract base class. By doing this, we are able to model that the idea of an employee is completely valid; it is just not a concrete entity. Also understand that although we cannot directly create an abstract class, it is still assembled in memory when derived classes are created. Thus, it is perfectly fine (and common) for abstract classes to define any number of constructors that are called indirectly when derived classes are allocated.

Intermediate Language (IL)

Despite the fact that .NET binaries take the same file extension as unmanaged Windows binaries (*.dll or *.exe), they have absolutely no internal similarities. Specifically, .NET binaries do not contain platform-specific instructions, but rather platform-agnostic Intermediate Language (IL) and type metadata.

unchecked keyword

Disables the throwing of a System.OverflowException on a case-by-case basis.

Entity Framework

Entity Framework (EF) is an open source[2] object-relational mapping (ORM) framework for ADO.NET. It was a part of .NET Framework, but since Entity framework version 6 it is separated from .NET framework. The Entity Framework is a set of technologies in ADO.NET that support the development of data-oriented software applications. Architects and developers of data-oriented applications have typically struggled with the need to achieve two very different objectives. They must model the entities, relationships, and logic of the business problems they are solving, and they must also work with the data engines used to store and retrieve the data. The data may span multiple storage systems, each with its own protocols; even applications that work with a single storage system must balance the requirements of the storage system against the requirements of writing efficient and maintainable application code. The Entity Framework enables developers to work with data in the form of domain-specific objects and properties, such as customers and customer addresses, without having to concern themselves with the underlying database tables and columns where this data is stored. With the Entity Framework, developers can work at a higher level of abstraction when they deal with data, and can create and maintain data-oriented applications with less code than in traditional applications.

Default constructor

Every C# class is provided with a freebee default constructor that you may redefine if need be. By definition, a default constructor never takes arguments. After allocating the new object into memory the default constructor ensures that all field data of the class is set to an appropriate default value.

Generics

Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which 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. For example, 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, as shown here: // Declare the generic class. public class GenericList<T> { public void Add(T input) { } } class TestGenericList { private class ExampleClass { } static void Main() { // Declare a list of type int. GenericList<int> list1 = new GenericList<int>(); list1.Add(1); // Declare a list of type string. GenericList<string> list2 = new GenericList<string>(); list2.Add(""); // Declare a list of type ExampleClass. GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); list3.Add(new ExampleClass()); } }

virtual keyword

If a base class wants to define a method that may be (but does not have to be) overridden by a subclass, it must markt he method with the virtual keyword.

(none) parameter modifier keyword

If a parameter is not marked with a parameter modifier, it is assume to be passed by value, meaning the called method receives a copy of the original data.

Partial keyword

If you want, you can partition a single class across multiple C# files, to isolate the boilerplate code from more readily useful members. E.g. partial class Employee { // some bullshit }

Restrictions on the var keyword

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.

Static keyword

In C# terms, "static" means "relating to the type itself, rather than an instance of the type". You access a static member using the type name instead of a reference or a value, e.g. Guid.NewGuid(). In addition to methods and variables, you can also declare a class to be static (since C# 2.0). A static class cannot be instantiated and can only contain static members. There are a few rules around static classes: Static classes always derive from object, you can't specify a different base type Static classes cannot implement an interface Static classes cannot have any instance members Static classes can't declare any constructors and the compiler doesn't create a parameterless constructor by default Static classes are implicitly abstract, you can't add the abstract modifier yourself Static classes may be generic Static classes may be nested, in either non-static or static classes Static classes may have nested types, either non-static or static Only static, top-level non-generic classes can contain extension methods (C# 3.0)

Encapsulation

Keeping details (like data and procedures) together in one part of a program so that programmers working on other parts of the program don't need to know about them. The language's ability to hide unnecessary implementation details form the object user, e.g. the multiple lines of code required to open and close a file.

Common Type System (CTS)

Key building block of .NET. The CTS specification fully describes all possible data types and all programming constructs supported by the runtime, specifies how these entities can interact with each other, and details how they are presented in the .NET metadata format.

Common Language Runtime (CLR)

Key building block of .NET. The primary role of the CLR is to locate, load and manage .NET objects on your behalf. The CLR also takes care of a number of low=level details such as memory management, application hosting, coordinating threads, and performing security checks (among other low-level details).

Readonly fields

Like a constant, a read-only field cannot be changed after the initial assignment. However, unlike a constant, the value assigned to a read-only field can be determined at runtime and, therefore, can legally be assigned with the scope of a constructor, but nowhere else. This can be very helpful when you don't know the value of a field until runtime, perhaps because you need to read an external file to obtain the value, but wish to ensure that the value will not change after that point.

named parameters

Named arguments allow you to invoke a method by specifying parameter values in any order you choose. Thus, rather than passing parameters solely by position (as you do in most cases), you can choose to specify each argument by name using a colon operator.

Can you inherit from more than one base class?

No, a given child class can inherit from only ONE base class. Unlike in unmanaged C++, for example, which allows for 'multiple inheritance' or MI.

out parameter modifier keyword

Output parameters must be assigned by the method being called, and the therefore, are passed by reference. If the called method fails to assign output parameters, you are issued a compiler error.

HTTP Put vs. Post

Overall: Both PUT and POST can be used for creating. You have to ask "what are you performing the action to?" to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST then you would do that to a list of questions. If you want to use PUT then you would do that to a particular question. Great both can be used, so which one should I use in my RESTful design: You do not need to support both PUT and POST. Which is used is left up to you. But just remember to use the right one depending on what object you are referencing in the request. Some considerations: -Do you name your URL objects you create explicitly, or let the server decide? If you name them then use PUT. If you let the server decide then use POST. -PUT is idempotent, so if you PUT an object twice, it has no effect. This is a nice property, so I would use PUT when possible. -You can update or create a resource with PUT with the same object URL -With POST you can have 2 requests coming in at the same time making modifications to a URL, and they may update different parts of the object.

Object initialization syntax

Point anotherPoint = new Point(); Point anotherPoint = new Point(20, 20); Point anotherPoint = new Point { X = 30, Y = 30 }

Write-only/Read-only properties

Read-only properties omit the set block, write-only properties omit the get block.

Interface Types vs. Abstract Base Classes

Recall that when a class is marked as abstract, it may define any number of abstract members to provide a polymorphic interface to all derived types. HOwever, even when a class does define a set of abstract members, it is also free to define any number of constructors, dfield data, non-abstract members (with implementation), and so on. Interfaces, on the other hand, contain ONLY abstract member definitions. The polymorphic interface established by an abstract parent class suffers from one major limitation in that only derived types support the members defined by the abstract parent. However, in larger software systems, it is very common to develop multiple class hierarchies that have no common parent types, we have no way to configure types in difference hierarchies to support the same polymorphic interface.

Sealed class

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET, NotInheritable keyword serves the purpose of sealed. If a class is derived from a sealed class, compiler throws an error. If you have ever noticed, structs are sealed. You cannot derive a class from a struct. You can also use the sealed modifier on a method or a property that overrides a virtual method or property in a base class. This enables you to allow classes to derive from your class and prevent other developers that are using your classes from overriding specific virtual methods and properties. The main purpose of a sealed class is to take away the inheritance feature from the user so they cannot derive a class from a sealed class. One of the best usage of sealed classes is when you have a class with static members. For example, the Pens and Brushes classes of the System.Drawing namespace. The Pens class represent the pens for standard colors. This class has only static members. For example, Pens.Blue represents a pen with blue color. Similarly, the Brushes class represents standard brushes. The Brushes.Blue represents a brush with blue color. So when you're designing your application, you may keep in mind that you have sealed classes to seal user's boundaries.

ildasm.exe

Shows the structure of an assembly using a familiary tree-view format

Structs

Structure types are well suited for modeling mathematical, geometrical, and other "atomic" entities in your application. A structure (like 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.You can think of a structure as a lightweight class type, given that structures provide a way to define a type that supports encapsulation, but cannot be used to build a family of related types. When you need to build a family of related types through inheritance, you will need to make use of class types. Unlike arrays, strings, or enumerations, structs do not have an identically named representation in the .NET library (that is, there is no System.Structure class), but are implicitly derived from System.ValueType. Simply put, the role of System.ValueType is to ensure that the derived type (e.g., any structure) is allocated on the stack, rather than the garbage-collected heap. Simply put, data allocated on the stack can be created and destroyed very quickly, as its lifetime is determined by the defining scope.

Core members of System.Object

System.Object is the default base class of all objects. Its core members include the .Equals(), .Finalize(), .GetHashCode(), .ToString(), .GetType(), and .MemberwiseClone(). See attached. You can override all these.

Just In Time compilation (JIT)

The .NET runtime environment leverages a JIT compiler for each CPU targeting the runtime, each optimized for the underlying platform, e.g. a low-memory mobile environment or a high-memory desktop one.

HTTP Post

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. In other words, POST is used to create.

HTTP Put

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI." That is, PUT is used to create or update.

Base Class Libraries

The base class libraries define types that can be used to build any type of software application. For example, you can use ASP.NET to build websites, WCF to build networked services, WPF to build desktop GUI applications, etc.

base keyword

The base keyword indicates a derived constructor is passing data to the immediate parent constructor. E.g.: public SalesPerson (string fullName, int age, int empID, float currPay, string ssn, int numbOfSales) : base(fullName, age, empID, currPay, ssn)

Casting rules for base classes/abstract classes (implicit cast)

The first law of casting between class types is that when two classes are related by an "is-a" relationship, it is always safe to store a derived object within a base class reference. Formally, this is called an 'implicit cast.' You don't have to use the parentheses as done with an explicit cast.

Inheritance

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

Protected keyword

The protected keyword is a member access modifier. This page covers protected access. The protected keyword is also part of the protected internal and private protected access modifiers. A protected member is accessible within its class and by derived class instances. A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type. In this example, the class DerivedPoint is derived from Point. Therefore, you can access the protected members of the base class directly from the derived class.

sealed keyword

The sealed keyword prevents inheritance from occurring. When you mark a class as sealed, the compiler will not allow you to derive form this type. Most often, sealing a class makes the best sense when you are designing a utility class. For example, the System namespace defines numerous sealed classes. Structs in C# are always implicitly sealed. Therefore, you can never derive one structure from another structure, a class from a structure, or a structure from a class. When building class hierarchies, you might find that a certain branch in the inheritance chain should be "capped off," as it makes no sense to further extend the linage.

ref parameter modifier keyword

The value is initially assigned by the caller and may be optionally reassigned 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.

?? operator

This operator allows you to assign a value to a nullable type if the retrieved value is in fact null.

params parameter modifier keyword

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 the C# language feature.

Abstract base class: polymorphic interface

This simply refers to an abstract base class's set of virtual and abstract methods. This is much more interesting than first meets the eye, as this trait of OOP allows you to build easily extendable and flexible software applications.

Abstract methods

To force each child class to override a method in the abstract class, you can define the method as an 'abstract' method. To do so, you use the abstract keyword. Abstract methods do not provide for any implementation whatsoever. E.g., public abstract void Draw(); Abstract methods can only be defined in abstract classes. If you attempt to do otherwise, you will be issued a compiler error. Child classes inheriting from the abstract class are required to override the abstract method. If they do not, the child class is also assumed to be a noncreatable abstract type that must be adorned with the abstract keyword (which is obviously not very useful in this example).

Abstract methods

To force each child class to override the Draw() method, you can define Draw() as an abstract method of the Shape class, which by definition means you provide no default implementation whatsoever. To mark a method as abstract in C#, you use the abstract keyword. E.g. public abstract void Draw(); Methods marked with the abstract keyword are pure protocol. They simply define the name, return type (if any), and parameter set (if required). Here, the abstract Shape class informs the derived types "I have a method named Draw() that takes no arguments and returns nothing. If you derive from me, you figure out the details." If you don't override it, the child class you're implementing is also assumed to be a noncreatable abstract type that must be adorned with the abstract keyword (which is obviously not very useful).

Static readonly fields

Unlike a constant field, read-only fields are not implicitly static. Thus, if you want to expose a readonly field from the class level, you must explicitly make use of the static keyword. If you know the value of a static readonly field at compile time, the initial assignment looks very similar to that of a constant (however in this case, it would be easier to simply use the const keyword in the first place, as we are assigning the data field at the time of declaration).

Value Types vs. Reference Types

Unlike arrays, strings, or enumerations, structs do not have an identically named representation in the .NET library (that is, there is no System.Structure class), but are implicitly derived from System.ValueType. Simply put, the role of System.ValueType is to ensure that the derived type (e.g., any structure) is allocated on the stack, rather than the garbage-collected heap. Simply put, data allocated on the stack can be created and destroyed very quickly, as its lifetime is determined by the defining scope. By default, when a value type contains other reference types, assignment results in a copy of the references. In this way, you have two independent structures, each of which contains a reference pointing to the same object in memory (i.e. a shallow copy). When you want to perform a deep copy, where the state of internal references is fully copied into a new object, one approach is to implement the ICloneable interface. It is possible to alter the object's state data. What is not possible is to reassign what the reference is pointing to. If a reference type is passed by reference, the callee may change the values of the object's state data, as well as the object it is referencing. If a reference type is passed by value, the callee may change the values of the object's state data, but not the object it is referencing.

this keyword

Used to resolve scope ambiguity, which ideally you would resolve through a naming convention that does not result in such ambiguity. For example, in a class Motorcycle: public int driverIntensity; public string driverName; public void SetDriverName(string name) { //These two statements are functionally the same driverName = name; this.driverName = name; }

protected keyword

When a base class defines protected data or protected members, it establishes a set of items that can be accessed directly by any descendent. The benefit of defining protected members in abase class is that derived types no longer have to access the data indirectly using public methods or properties. The possible downfall, of course, is that when a derived type has direct access to its parent's internal data, it is very possible to accidentally bypass existing business rules found within public properties. WHen you define protected members, you are creating a level of trust between the parent and child class, as the compiler will not catch any violation of your type's business rules.

Abstract classes: understanding the polymorphic interface/abstract members

When a class has been defined as an abstract base class (via the abstract keyword), it may define any number of abstract members. Abstract members can be used whenever you wish to define a member that does not supply a default implementation, but must be accounted for by each derived class. BY doing so, you enforce a polymorphic interface on each descendent, leaving them to contend with the task of providing the details behind your abstract methods. Simply put, an abstract base class's polymorphic interface simply refers to its set of virtual and abstract methods. E.g., when you don't want to allow the object user to create an instance of the Shape class directly, because it's too abstract. If the child class chooses, it may override the virtual method of the base class but it does not have to. E.g., Shape[] myShapes = { new Hexagon(), new Circle, new Hexagon("Mick")};

override keyword

When a subclass wants to change the implementation details of a virtual method, it does so using the override keyword. You can use the base keyword to leverage the default behavior of the method in the parent class, e.g.: public override void GiveBonus(float amount) { base.GiveBonus(amount); Random r = new Random(); StockOptions += r.Next(500); }

checked keyword

When you wrap a statement (or a block of statements) within the scope of the checked keyword, the C# compiler emits additional CIL instructions that test for overflow conditions that may result when adding, multiplying, subtracting, or dividing two numerical data types. If an overflow has occurred, you will receive a runtime exception: System.OverflowException.

Dynamic typing (scripting languages like JavaScript or Perl)

Where a variable can hold values of different types over its lifetime in a program. Vs. implicit typing of local variables that results in strongly typed data.

Windows Communication Foundation (WCF)

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include: A secure service to process business transactions. A service that supplies current data to others, such as a traffic report or other monitoring service. A chat service that allows two people to communicate or exchange data in real time. A dashboard application that polls one or more services for data and presents it in a logical presentation. Exposing a workflow implemented using Windows Workflow Foundation as a WCF service. A Silverlight application to poll a service for the latest data feeds. While creating such applications was possible prior to the existence of WCF, WCF makes the development of endpoints easier than ever. In summary, WCF is designed to offer a manageable approach to creating Web services and Web service clients.

Windows Presentation Foundation (WPF)

Windows Presentation Foundation (WPF) is a graphical subsystem by Microsoft for rendering user interfaces in Windows-based applications. WPF, previously known as "Avalon", was initially released as part of .NET Framework 3.0 in 2006. WPF uses DirectX and attempts to provide a consistent programming model for building applications. It separates the user interface from business logic, and resembles similar XML-oriented object models, such as those implemented in XUL and SVG. WPF employs XAML, an XML-based language, to define and link various interface elements.[1] WPF applications can be deployed as standalone desktop programs or hosted as an embedded object in a website. WPF aims to unify a number of common user interface elements, such as 2D/3D rendering, fixed and adaptive documents, typography, vector graphics, runtime animation, and pre-rendered media. These elements can then be linked and manipulated based on various events, user interactions, and data bindings. WPF runtime libraries are included with all versions of Microsoft Windows since Windows Vista and Windows Server 2008. Users of Windows XP SP2/SP3 and Windows Server 2003 can optionally install the necessary libraries.[2][3] Microsoft Silverlight provided functionality that is mostly a subset of WPF to provide embedded web controls comparable to Adobe Flash. 3D runtime rendering had been supported in Silverlight since Silverlight 5.[4]

sealed override

You sometimes might not wish to seal an entire class, but simply want to prevent derived types from overriding particular virtual methods. E.g. you can seal the method in a parent class by using "public override sealed void GiveBonus(float amount)".

private keyword

can only be accessed by the defining type or class. Nonnested types cannot be marked private!

Nested types

e.g., public class OuterClass { public/private class PublicInnerClass/PrivateInnerClass ... } Why would you want to use a nested type? Nested types allow you to gain complete control over the access level of the inner type, as they may be declared privately (recall that non-nested classes cannot be declared using the private keyword). Because a nested type is a member of the containing class, it can access private members of the containing class. Often, a nested type is only useful as a helper for the outer class, and is not intended for use by the outside world.

Inheritance and containment/delegation: two flavors

inheritance the "is-a" relationship, containment/delegation is the "has-a" relationship.

Array initialization syntax

string[] stringArray = new string[] bool[] boolArray = { false, false, true} int[] intArray = new int[4] { 20, 22, 23, 0 } implicit with var test = new[] { 2, 2, 2}

Automatic property syntax

{ get; set; } When you use automatic properties to encapsulate numerical or Boolean data, you are able to use the auto-generated type properties straightaway within your code base, as the hidden backing fields will be assigned a safe default value that can be used directly. However, be very aware that if you use automatic property syntax to wrap another class variable, the hidden private reference type will also be set to a default value of null.


Ensembles d'études connexes

Administrative Law - Prof. Stevenson

View Set

Purdue CNIT 155 Midterm Exam (Python)

View Set

Chapter 2: Workforce Safety and Wellness

View Set

28. Examining the Cisco SD-Access Solution

View Set