Posts
consistent model for working with data from various kinds of sources and formats (XML, SQL, ADO.NET, Datasets, .NET collections etc) 3 stages of working with LINQ: obtain data source create the query execute the query data sources implements IEnumerable<> and are called queryable types IQueryable<> interface inherits from IEnumerable<> generally it is better to use LINQ via IQueryable<> which produces deferred query instead of producing result immediately queries can be executed multiple times queries can be forced immediate execution via Count(), Max(), ToList() or ToArray() etc. LINQ to DB libraries (like EntityFramework) usually are implemented via Expression …
Entity Framework: Change Tracking
tracked entities are saved during SaveChanges() call entities being tracked when they are: returned from DB attached to context added as subentity tracking can be disabled (AsNoTracking() i.e.) Further read:
https://learn.microsoft.com/en-us/ef/core/change-tracking/
Entity Framework: eager and lazy loading
lazy loading:
- delaying load of data until we specifically request for it
- i.e. accessing
customer.Addressloads Address of a customer in the background via separate SQL query
- property needs to be public, virtual
- context.Configuration.ProxyCreationEnabled should be true
- context.Configuration.LazyLoadingEnabled should be true
- to disable lazy loading completely
Context.Configuration.LazyLoadingEnabled = false;
eager loading
- opposite of lazy loading
- loads related entities as part of the query
- done via
.Include()query
Further read:
Pattern matching
Pattern matching is used for:
testing expression to check if some value have certain characteristics safer compare because ‘==’ and ‘!=’ can be overloaded Examples:
a is int number sequence is IList<T> list switch statement:
command switch { Operation.SystemTest => RunDiagnostics(), Operation.Start => StartSystem(), Operation.Stop => StopSystem(), Operation.Reset => ResetToReady(), _ => throw new ArgumentException("Invalid enum value for command", nameof(command)), }; switch with ranges:
tempInFahrenheit switch { (> 32) and (< 212) => "liquid", < 32 => "solid", > 212 => "gas", 32 => …
Reflection
obtain information about types and members at runtime create instances, invoke or access them dynamic code generation Further read:
https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection
Deployment models
Type Command framework-dependent executable for the current platform. dotnet publish framework-dependent executable for a specific platform. dotnet publish -r <RID> --self-contained false framework-dependent binary. dotnet publish self-contained executable. dotnet publish -r <RID> Further read:
https://learn.microsoft.com/en-us/dotnet/core/deploying/#publish-framework-dependent
.NET AOT
Ahead of the time compilation to machine code
produces self-contained application which: starts quicker uses less memory does not require .NET runtime installed it is better for workloads with high deployment instances (clouds) makes runtime code generation impossible not all libraries are compatible Further read:
https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/
.NET Jit
Just - in - time compiler.
part of CLR for all .net programs for all .net languages converts MSIL to native machine code compiles code when it is necessary at runtime also it is possible to pre-compile to native code at compile time instead Further read:
https://www.geeksforgeeks.org/what-is-just-in-time-jit-compiler-in-dot-net/
Records
can be class or struct creates methods overrides for enforcing value equality instead of reference equality: Object.Equals Object.GetHashCode operators == != implements IEquatable<> parameter implements ToString supports deconstruction supports with expression meant to be immutable Positional records is a more concise syntax for record:
primary constructor parameters match the positional parameters of the record declaration public init-only properties for each parameter Further read:
https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records#characteristics-of-records
Is it possible to block GC?
We can.
for some critical part of application code using GC.TryStartNoGCRegion method. using CER (Constrained Execution Regions) (obsolete) with GC LatencyModes Further read:
https://learn.microsoft.com/en-us/dotnet/api/system.gc.trystartnogcregion?redirectedfrom=MSDN&view=net-7.0#overloads https://learn.microsoft.com/en-us/dotnet/framework/performance/constrained-execution-regions?redirectedfrom=MSDN https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/latency
Garbage Collector
automatic memory management allocates and releases memory prevents memory leaks and accessing dead objects provides memory safety virtual memory space defragments/compacts memory heap have 3 generations 0 - for new objects; 1 - for objects that lives through GC from 0 2 - for long living objects from 1 and 0 also Large Objects Heap (LOH) for big objects like arrays over 85,000 bytes Further read:
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals?source=recommendations
Covariance and Contravariance
- enables implicit reference conversions for
- arrays
- delegates
- generic type arguments
- Covariance preserves assignment compatibility
- Contravariance reverses assignment compatibility
- allows for matching signatures of delegates and method groups
- to assign to delegates from method that returns more derived types - covariance
- to assign to delegates from method that returns less derived types - contravariance
- Covariance and Contravariance are supported in Generics for implicit conversions for type parameters
- allows method to have more derived return type than defined by generic type parameter of the interface
- this allows implicit conversions from one generic interface to another (from
IEnumerable<string>toIEnumerable<object>even if first does not inherits from second) - allows generic types to have less derived argument types than specified by the generic parameter of the interface (implementation of
IEqualityComparer<BaseClass>can be implicitly converted toIEqualityComparer<DerivedClass>becauseIEqualityComparer.Equalsis contravariant) - implicit conversions works for interfaces but not classes that implement from those interfaces (i.e. this won’t work
List<Object> list = new List<String>())
Assignment compatibility is when object of a more derived type is assigned to an object of a less derived type.
.NET Generics
Allow for:
- generalization of logic based on available types
- specify possible supported types
- re-usability of code
- type safety
- defers the exact specification of logic until the class or method is declared and instantiated by user code with all type parameters specified
- mostly used for collections (some non-generic versions of collection are not recommended like
ArrayListi.e.) - information of exact type parameters used in a generic can be obtained at runtime by reflection
Further read:
Data structures in .NET
In table below official recommendations for choosing data structure for your needs:
| Generic | Non-Generic | Thread safe | Purpose |
Dictionary | Hashtable | ConcurrentDictionary | key value pairs, lookup |
List | Array | ImmutableList | access items by index |
Queue | - | ConcurrentQueue | FIFO queue |
Stack | - | ConcurrentStack | LIFO queue |
LinkedList | - | - | access items sequentially |
ObservableCollection | - | - | notfications after modification |
SortedList | ImmutableSortedSet | auto sorted collection | |
HashSet | ImmutableHashSet | dictionary of just keys (high performance set operations) |
Further read:
Strings in .NET
sequential collection of chars immutable max 2GB or about 1 billion characters reference type are interned - CLR saves memory by maintaining a table, called the “intern pool”, that contains a single reference to each unique literal string declared or created programmatically in your program. Further read:
https://learn.microsoft.com/en-us/dotnet/api/system.string?view=net-7.0 https://learn.microsoft.com/en-us/dotnet/api/system.string.intern?view=net-6.0#remarks