📜 ⬆️ ⬇️

Answers to ".Net Questions"

In my POST post, I asked a few questions about .NET and clr and promised to answer them. I answer:

1) When during the creation of an instance of a type the constructor will not be called?
I know 2 cases: when deserializing an object and when copying an object using the MemberwiseClone method of an Object

2) How does the c # compiler interpret the static modifier before the class (in IL code)?
In the IL code there will be something like the following:
class public abstract auto ansi sealed beforefieldinit .
besides, the compiler will also not create a constructor method in the class

3) Which field access modifier does not implement c #, but does IL code?
family and assembly — available only to methods in the defining type (and nested types) and derived types in the defining assembly
')
4) Do you know how to declare Union (imitate) in C #? Those. make several fields start one shift in memory.
[StructLayout(LayoutKind.Explicit)]
internal struct SomeValType {
[FieldOffset(O)] Byte b; // b
[FieldOffset(O)] Int16 x; // .
}


5) Have you ever wondered why it is impossible to define a constructor without parameters (in C #) for meaningful types (struct)? Is it possible to get around this? :)
C # does not allow defining constructors with no parameters for meaningful types, so as not to mislead developers as to which constructor is called (the one that initializes everything with zeros, or ours)
On IL, unlike c #, you can define such a constructor. (how it will work is another question)

6) If we put a code to the client where the fields were defined in the type, the client wrote his code based on our code, then we delivered the client a new version of our code where the fields are replaced with properties, then what could be broken in the client’s code?
Of course, first of all, all methods will cease to compile, where the parameters were fields (and now properties) with out or ref ... In addition -
property can be read only,
property method may result in an exception
property method can be long
when calling several rows in a row, the property can return different values ​​(4Ex.:DateTime.Now)
In addition, if you used reflection, then when binding, there will also be an event.

7) All event handlers must return void ... Does Microsoft follow its requirement in the FCL library? :))
Indeed, such a requirement is embedded in the mechanism of events. This is mandatory, because when an event occurs it may trigger several callback methods and it will not be possible to get their return value.
Microsoft, as always, in its own spirit - its recommendations should not be - an example of the event handler ResolveEventHandler, which returns an object of type Assembly. (proof link: tyts )

PS Questions and answers prepared by the book CLR via C # Jeffrey Richter ...

Source: https://habr.com/ru/post/61969/


All Articles