C#. Attributes

Definition

Attributes – descendants of System.Attribute, some kind of annotations of code, applied for some object.

Standart attributes are

[CLSCompliant] – Common Language Specification

[DLLImport]

[Obsolete] – deprecated

[Serializable]

[NonSerialized]

[WebMethod]

Self made attributes also possible

Attribute consumers

Compiler,

some methods of .NET – for example BinaryFormatter,

CLR

SimpleExample

Writing like this will add errors to Error list because we used Obsolete

 

ShortNames of Attributes

[SerializableAttribute] and [Serializable] the same in C#

Attributes may recieve params in constructor

CustomAttributes

AttributedCarLibrary.cs

use of custom attributes

AttributeLimitations

we can use class AttributeTargets like this

Assembly level attributes

  1. Solution Explorer – > Properties – > AssemblyInfo.cs – fill attributes right in assembly
  2. Also you can write in code before namespace

Reflection Attributes with EarlyBinding

full example

Reflection Attributes with lateBinding

 

Posted in C# | Comments Off on C#. Attributes

С#. LateBindingExamples

Late binding means – we can create instance not in compilation time but in execution and call methods with or without params

-invoke methods with / without params

-setting private fields

 

Posted in C# | Comments Off on С#. LateBindingExamples

C#. Dynamically loaded assembly

Load and LoadFrom commands…

This will give

 

Posted in C# | Comments Off on C#. Dynamically loaded assembly

C#. Reflection

Reflection – getting info about type during execution.

#1 Need instance and info about type, before getting type

#2 Need info about type before getting type

#3 in current assembly with string param

#4 in external assembly GAC

#5 for generic types

 

Reflection of methods, fields, properties,

 

Posted in C# | Comments Off on C#. Reflection

C#. Shared assembly

Lets use Carlib.dll from One file Assembly

1. Strong name

Properties – > Signing – > Sign the assembly -> New – > SomeName (for ex. myKeyPair.snk)

2.  Install assembly to GAC (Global Assembly Cache)

go to

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\Visual Studio Tools\Developer Command Prompt for VS2015

start Developer Command Prompt for VS2015 with Admin rights

write something like

C:\C#\MyC#StudyProjects\07_DifferentMains\CarLibrary\CarLibrary\bin\Debug>gacutil -i CarLibrary.dll

and receive

Сборка успешно добавлена в кэш

check if assembly in GAC

C:\C#\MyC#StudyProjects\07_DifferentMains\CarLibrary\CarLibrary\bin\Debug>gacutil -l CarLibrary

and receive

В глобальном кэше сборок содержатся следующие сборки:
CarLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6a9228aea5de13fa, processorArchitecture=MSIL

Число элементов = 1

3. Use  assembly

In MS Visual Studio – Class View – right click add Reference – > Browse

add assembly to solution… go to…

C:\Windows\Microsoft.NET\assembly\GAC_MSIL\CarLibrary\v4.0_1.0.0.0__6a9228aea5de13fa

and add CarLib.dll

4. Use it in project – now assembly not copied to location of program

 

Posted in C# | Comments Off on C#. Shared assembly

С#. Assembly theory

Assemblyversioned (for ex. 1.0.0.0), self described( has manifest, links to other external assemblies, info about all types) binary, supported by CLR (Common Language Runtime). One EXE is divided in may exe, dll files.

Assembly defines type borders.  Example.  Both MyCars.dll and YourCars.dll has CarLibrary that has SportsCar class. It will be 2 different classes.

Private assembly – in the same catalogue with client app.

Shared Assembly – in Global Assembly Cache

Assembly consists of:

  • Windows headers file
  • CLR headers file
  • CIL code
  • Types metadata
  • Manifest
  • Additional resources

Windows headers file

(

how to open it?

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2015\Visual Studio Tools\Developer Command Prompt for VS2015

for example

Dump of file C:\C#\MyC#StudyProjects\07_DifferentMains\nameSpaceExamples\nameSpaceExamples\bin\Debug\nameSpaceExamples.exe

)

CLR Headers file

dumpbin /clrheader C:\C#\MyC#StudyProjects\07_DifferentMains\nameSpaceExamples\nameSpaceExamples\bin\Debug\nameSpaceExamples.exe

CIL code compiled on current platform with JIT (Just in time compiler)

Type metadata – where in binary types ?

Manifest – list of modules, version, all external assemblies

Additional resources for pics and other files. Also satellite assemblies possible.

One file and many files assemblies

module – binary file of .NET

One file assembly Carlibrary.dll

Many files assembly – many files with *.netmodule extension and one main file (*.exe or *.dll) and one version number. Main file and *.netmodules have manifests. it is one logically, but on physics level – many files

Advantage – can be loaded when needed (dynamically), allows use different programming languages (like dll in Delphi).

Posted in C# | Comments Off on С#. Assembly theory

C#. Creating one file assembly. Example

Lets create CarLibrary.dll assembly

File NewProject ClassLibrary

In other file Derived.cs 2 derived classes

ClassView – addReference – System.Windows.Forms

Now lets create new project CarClient

ClassView – addReference – Browse –  CarLibrary.dll

 

Posted in C# | Comments Off on C#. Creating one file assembly. Example

C#. Namespace examples

123

Circle.cs

Hexagon.cs

Square.cs

 

Posted in C# | Comments Off on C#. Namespace examples

C#. Delegates, Func, Action

Ну, есть ключевое слово delegate — это описание сигнатуры функции, т. е., её списка параметров и типа возвращаемого значения. Используется так:

Им можно пользоваться так:

С другой стороны, есть готовые, предопределённые сигнатуры функций (Func<TArg1, TArg2, ..., TResult> с возвращаемым значением, Action<TArg1, Targ2, ...> без). То есть, можно не определять делегат самому, а воспользоваться готовыми Func и Action. Аналогичный пример:

Если для вашей сигнатуры подходит Func или Action, особого смысла определять свой делегат нету. Или есть, если вы хотите дать своему делегату более подходящее имя, чем просто Func, и хотите подчеркнуть его семантику.

Существуют случаи, когда свой делегат всё же необходимо объявлять. Например, наличие out– и ref-параметров:

Для полноты, вот (надеюсь, полный) список вариантов, когда вам придётся объявлять делегат:

  • Когда список аргументов чересчур длинный (для .NET 4+ более 16 аргументов, для .NET 3.5 больше 4 аргументов)
  • Когда ваши аргументы содержат refout или params.
  • Если ваш делегат рекурсивен (например delegate D D(D d)). Как ни странно, такие штуки иногда нужны.
Posted in C# | Comments Off on C#. Delegates, Func, Action

C#. Func template for delegates

123

 

Posted in C# | Comments Off on C#. Func template for delegates