C# 1001 notes
6.51K subscribers
328 photos
9 videos
2 files
313 links
Регулярные короткие заметки по C# и .NET.

Просто о сложном для каждого.

admin - @haarrp
加入频道
​​Using DefaultValue Attribute

You can assign the default value using the DefaultValueAttribute attribute, as shown below.

💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes
​​In C#, the Scope of the variable determines the accessibility of the variable to a particular part of the application. Variables can be declared within the class, method, and code block of a loop, condition, etc.

There are three types of scopes in C#.

- Class Level Scope
- Method Level Scope
- Code-Block Level Scope

Class Level Scope

A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.

In the above example, the Student class contains two class variables (a.k.a. fields) _firstName and _lastName. These fields can be accessed anywhere within the class, i.e., within any non-static methods and properties.

The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.
​​Method Level Scope

A variable declared within a method has a method level Scope. It is also known as a local variable of the method where it is declared. It cannot be accessed outside the method.

Any nested code blocks within the method can access this type of variable. It cannot be declared twice with the same name within the same scope.

The local variable's scope ends when the method execution completes, and they will be collected by the garbage collector.

The following example shows the method Level scope.

In the above example, the Main() method can only access variables declared in the Main() method but not variables of other methods. In the same way, the Process() method cannot access variables declared in the Main() or any other method.
​​Code-Block Level Scope

A variable declared within a loop or any block within brackets has the code-block level scope. A variable declared within a loop or code block cannot be accessed outside of it, whereas a variable declared outside of the loop can be accessible within the loop.

In the above example, a variable i declared within a for loop. So, it can only be accessed within the for loop block and cannot be accessed outside for loop. In the same way, x is declared within the if block, so it can only be accessed in that block but not outside of it.

A variable must be declared outside of the code block to make it accessible to outside code.

💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
When to use Struct over Class in C# (part 1)

The Struct is a similar and lighter version of the class in C#. However, there are some pros and cons of Struct. After knowing this, you can understand when to use struct over class in c#.

Limitations of Struct:

🔸 Class is a reference type, whereas Struct is a value type.

🔸 A default constructor or destructor cannot be created in Struct.

🔸 Structs inherit from System.ValueType, cannot be inherited from another Struct or Class, and cannot be a base class.

🔸 Struct types cannot be abstract and are always sealed implicitly.

🔸 Struct members cannot be abstract, sealed, virtual, or protected.

🔸 Structs copy the entire value on the assignment, whereas reference types copy the reference on assignment. So, large reference type assignments are cheaper than the value types.

🔸 Instance field declarations in Struct cannot include variable initializers. But, static fields in Struct can include variable initializers.

🔸 A null value can be assigned to a struct as it can be used as a nullable type.

🔸 Structs are allocated either on the stack or inline in containing types and deallocated when the stack or the containing type gets deallocated. But, reference types are allocated on the heap and garbage-collected. So, the allocation and deallocation of structs are cheaper than classes.

🔸 Array elements of reference types are references to the instances of the reference types that exist on the heap, whereas array elements of value types are the real instances of the value type. So, allocation and deallocation of value type arrays are much cheaper than the reference type arrays.

🔸 Value types get boxed and unboxed during the typecasting. An excessive amount of boxing and unboxing results in a negative impact on the heap, garbage collector, and the application's performance.
When to use Struct over Class in C# (part 2)

Generally, the use of value types will affect fewer objects in the managed heap, less load on the garbage collector, and thus better performance. However, it has a drawback as well. Value types will become expensive in the case of a big Struct. Thus, before using Struct we should understand when to use Struct over Class in C#.

🔸 If all the member fields are value types.

🔸 If instances of the type are small and short-lived or embedded to other instances.

🔸 If it logically denotes a single value, same as primitive types like int, double, etc.

🔸 If the size of the instance is below 16 bytes.

🔸 If it will not be boxed and unboxed again and again
.
🔸 If it is immutable, that means when an instance of a reference type gets changed, it affects all the references indicating the instance. But, in the case of value types, it does not affect any of its copies. For this reason, changes in value types may raise confusion in many users. So, it should be immutable.
​​Convert int to Enum by Type Casting

You can explicitly type cast an int to a particular enum type, as shown below.
​​Convert int to Enum using Enum.ToObject() Method

Use the Enum.ToObject() method to convert integers to enum members, as shown below.
​​Convert an Object to JSON in C#

Here you will learn how to convert C# object to JSON using Serialization.

JSON (Javascript Object Notation) is used for storing and data transfer. It is also used in API calls to exchange the data from API to different web applications or from browser to server and vice versa.

Serialization is the process of storing the state of an object and being able to recreate it when required. The reverse of it is known as Deserialization.

The .NET 5 framework provides the built-in JsonSerializer class in the System.Text.Json namespace to convert C# objects to JSON and vice-versa.

The .NET 4.x framework does not provide any built-in JsonSerializer class that converts objects to JSON. You have to install the NuGet package Microsoft.Extensions.Configuration.Json in your project to include the System.Text.Json.JsonSerializer to your project which can be used to convert objects to JSON and vice-versa.
​​Convert an Object to a Minified JSON String

The following example shows the conversion of an object to the formatted JSON string:

In the above example, we specified an option with WriteIndented=true as a parameter in the Serialize() method. This will return a formatted string with indentation.
​​Convert a List to a JSON String

The following converts a list collection of objects to JSON array.
​​Convert an Object to a UTF-8 String

Serialization to an utf-8 byte array is a bit faster than the string method. This is because the bytes of utf-8 is not required to convert to strings of utf-16.

The following example shows the conversion of an object to a minified JSON string using JsonSerializer.SerializeToUtf8Bytes method.

Thus, you can convert C# object to JSON in different ways for different versions using JsonConvert.Serialize() method in .NET 4.x and .NET 5.
Forwarded from C# (C Sharp) programming
⚜️ Подборка Топ-10 поезныйх библиотек для разработчиков .NET

1) Newtonsoft.Json: Эта библиотека широко используется для работы с данными JSON в приложениях .NET. Newtonsoft.Json обеспечивает высокую производительность и простоту использования, что делает ее отличным решением для сериализации и десериализации данных JSON.

2) Dapper: Это простой и эффективный ORM, который обеспечивает высокую производительность и гибкость при работе с реляционными базами данных. Dapper прост в использовании и предлагает быстрый и эффективный способ взаимодействия с базами данных.

3) Polly: Polly - это библиотека, которая помогает легко обрабатывать ошибки в приложениях .NET.

4) AutoMapper: Эта библиотека .NET Core упрощает сопоставление объектов с объектами путем автоматического сопоставления свойств одного объекта с другим. Эта библиотека особенно полезна в больших проектах, где сопоставление может занять много времени и стать утомительным.

5) FluentValidation: Это библиотека, которая предоставляет API для построения правил валидации. Она позволяет легко создавать сложную логику проверки и поддерживает широкий спектр скриптов валидации, что делает ее полезным инструментом для обеспечения целостности данных в ваших приложениях.

6) Serilog: Эта библиотека представляет собой структурированную библиотеку протоколирования, которая упрощает сбор и анализ журналов вашего приложения. Она обеспечивает гибкость и расширяемость и поддерживает различные источники для хранения журналов, включая Elasticsearch, SQL Server и другие.

7) Swashbuckle.AspNetCore.Swagger: Эта библиотека генерирует документацию OpenAPI для вашего ASP.NET Core Web API. Она облегчает понимание функциональности вашего API и позволяет легко генерировать код для вашего API.

8) NLog: Это бесплатная платформа протоколирования для .NET с широкими возможностями маршрутизации и управления журналами.

9) Moq4: Это популярный фреймворк mocking для приложений .NET. Она позволяет легко создавать объекты для модульного тестирования.

10) StackExchange.Redis: Это библиотека для работы с базами данных Redis в приложениях .NET. Она предоставляет простой и эффективный способ взаимодействия с Redis, а также обеспечивает высокую производительность и масштабируемость.

@csharp_ci
Please open Telegram to view this post
VIEW IN TELEGRAM
Converting Strings to .NET Objects – IParsable and ISpanParsable

Преобразование строк в объекты .NET с использованием новых интерфейсов IParsable и ISpanParsable: на заметку C#-разработчику.

Читать

@csharp_1001_notes
Grouping a Collection

To group a collection using LINQ, you can use the GroupBy() method:

using System.Linq;

List<string> names = new List<string> { "John", "Jane", "Doe" };
var groups = names.GroupBy(x => x.Length);

foreach (var group in groups)
{
Console.WriteLine($"Names with {group.Key} characters:");
foreach (string name in group)
{
Console.WriteLine(name);
}
}


@csharp_1001_notes
Please open Telegram to view this post
VIEW IN TELEGRAM
Шаблон ASP.NET Core, построенный в соответствии с принципами чистой архитектуры

Шаблона предоставялет простой и эффективный подход к разработке корпоративных приложений, используя возможности чистой архитектуры и ASP.NET Core.

С его помощью вы можете легко создать одностраничное приложение с использованием ASP NET Core + Angular/React, придерживаясь принципов чистой архитектуры.

@csharp_1001_notes
Forwarded from C# (C Sharp) programming
This media is not supported in your browser
VIEW IN TELEGRAM
📣 Внимание C# разрабочики!

Сохраните этот пост и возвращайтесь к нему в любое время, когда вам понадобится освежить в памяти методы LINQ!

@csharp_ci