Lesson 11
During this lesson we’ll talk mostly about generic types and reflection. Also I’ll show a LINQ magic and generic types. This lesson shows only the top of the iceberg, More LINQ features and reflection will be shown in further lessons.
Agenda
- LINQ (Language-Integrated Query)
- Generics
- Generic Constraints
- System.Collections.Generic
- Attributes
- Reflection
- Exporter demo
- References
- Presentation
LINQ (Language-Integrated Query)
LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store.
All LINQ query operations consist of three distinct actions: - Obtain the data source - Create the query - Execute the query
Examples:
Please execute this code to see what will happen.
Generics
Generic classes encapsulate operations that are not specific to a particular data type.
T - is a type passed into the class.
This class can be used in a following way:
Please run this code to observe a result.
Generic Constraints is the thing designed to assign some requirements for a type that can be passed into the class. By default, a type parameter can be substituted with any type whatsoever. Constraints can be applied to a type parameter to require more specific type arguments:
- where T : base-class
// Base-class constraint - where T : interface
// Interface constraint - where T : class
// Reference-type constraint - where T : struct
// Value-type constraint (excludes Nullable types) - where T : new()
// Parameterless constructor constraint - where U : T
// Naked type constraint
Followign code demonstrates how it works.
Please notice that T is limited to be only a reference type. If we use this class with value type E.g. int, it’ll throw a compilation error:
System.Collections.Generic
The System.Collections.Generic namespace contains interfaces and classes that define generic collections, which allow users to create strongly typed collections that provide better type safety and performance than non-generic strongly typed collections.
Execute followign lines of code to see how collections works.
Attributes
Attributes extend classes and types. This C# feature allows you to attach declarative information, like some metadata information, to any type. .NET framework has Attribute class. You should do next steps to have your own attribute: 1) Create and new class with name ended with Attribute. 2) Inherit it from standard Attribute class. 3) Implement any functionality if necessary.
Example:
or
These attributes can be used as:
At the end of the lesson you can find a demo to see it in action.
Reflection
Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. Reflection is used to fetch attributes information for types.
Reflection examples:
Exporter demo
Download the source code demo by following this link.