uk
Feedback
C# 1001 notes

C# 1001 notes

Відкрити в Telegram

Регулярные короткие заметки по C# и .NET. Просто о сложном для каждого. admin - @haarrp

Показати більше
6 611
Підписники
-724 години
+477 днів
+4730 день
Архів дописів
​​Generate Random Number in Min to Max Range Use the Next(int min, int max) overload method to get a random integer that is within a specified range. In the above example, rnd.Next(10, 20) generate random numbers that will be between 10 to 19.

​​Generate Random Numbers in Range Use the Next(int) method overload to generate a random integer that is less than the specified maximum value. The following example generates the positive random numbers that are less than 10.

В канале t.me/DotnetBackendStudy выкладываются конспекты по различным темам направления .NET backend. Они помогут тебе как изучить что-то новое, так и подтянуть то, что уже забылось. Переходи и подписывайся.

​​Generate Random Numbers in C# (part 1) Here you will learn how to generate random numbers in C#. C# provides the Random class to generate random numbers based on the seed value. Use the following methods of the Random class to generate random numbers. The following example demonstrates how to generate a random integers. Call the Next() method multiple times to get the multiple random numbers, as shown below.

​​Solutions to fix the NullReferenceException (part 4) In .NET 4.x and above versions, use Null-Coalescing operator ?? to prevent an exception, as shown below: In the above example, ?? is a null coalescing operator that checks if an object is null or not, if it is null then create an object. The cities ?? new List<string>() creates a new list object if a cities is null in foreach loop. Thus, the NullReferenceException will be not be raised. 💬 Like this note? Want to support the channel? Become a patron: https://www.patreon.com/csharp1001notes

​​Бэкенд-разработчики на С++ пишут ПО под Linux, интегрируются с фронтендом, запускают проекты в Docker и получают 179 000 ₽ в месяц по данным Хабр Карьеры.  Хочется перейти на С++ и работать с такими задачами, но в резюме не хватает нужных навыков? Сделайте апгрейд стека на курсе Яндекс Практикума.  За 2 месяца студенты напишут проект бэкенда для небольшой игры и освоят такие инструменты:  → библиотеки boost:asio и boost:beast;  → СУБД PostgreSQL;  → сетевые протоколы TCP, UDP, HTTP;   → Docker;   → пакетный менеджер Conan;  → системы мониторинга, логирования и тестирования.  Вы не останетесь с вопросами один на один: наставники помогут разобрать сложные темы на вебинарах. Каждый спринт проект будет проходить код-ревью от опытных разработчиков уровня middle+.   Первый поток стартует 8 августа →

​​Solutions to fix the NullReferenceException (part 3) In .NET 5, use the null conditional operator ?., as shown below: In the above example, std?.FirstName is like if(std != null) std.FirstName. The std?.FirstName checks if std is not null then only access the FirstName property.

​​Solutions to fix the NullReferenceException (part 2) To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. Solution 1: Check whether an object contains a null value or not using an if condition, as shown below: In the above example, if(cities == null) checks whether the cities object is null or not. If it is null then display the appropriate message and return from the function.

​​NullReferenceException in C# (part 1) The NullReferenceException is an exception that will be thrown while accessing a null object. The following example shows the code that throws the NullReferenceException: In the above example, a NullReferenceException will be thrown in the DisplayCities() function while accessing cities list using a foreach loop because the cities list is null. If the caller of the DisplayCities() function pass a null IList value then it will raise a NullReferenceException.

​​How to loop through an enum in C#? (part 2) The Enum.GetValues<TEnum>() is a static method that retrieves an array of the constant values of the specified enum. The following example shows how to get the values of an enum using the Enum.GetValues<TEnum>() method. 💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes

​​How to loop through an enum in C#? (part 1) Here you will learn how to enumerate or loop through an enum. In C#, an enum is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.Monday is more readable than number 0 when referring to the day in a week. An enum can be looped through using Enum.GetNames<TEnum>()Enum.GetNames()Enum.GetValues<TEnum>(), or Enum.GetValues() static methods with the foreach loop. The following example gets the names of an enum using the Enum.GetNames<TEnum>() method.

​​Foreach Loop in C# (part 4) Beginning with C# 8.0, you can use the await foreach statement to consume an asynchronous stream of data, that is, the collection type that implements the IAsyncEnumerable<T> interface. Each iteration of the loop may be suspended while the next element is retrieved asynchronously. The following example shows how to use the await foreach statement: You can also use the await foreach statement with an instance of any type that satisfies the following conditions: 🔸 A type has the public parameterless GetAsyncEnumerator method. That method can be a type's extension method. 🔸 The return type of the GetAsyncEnumerator method has the public Current property and the public parameterless MoveNextAsync method whose return type is Task<bool>ValueTask<bool>, or any other awaitable type whose awaiter's GetResult method returns a bool value. By default, stream elements are processed in the captured context. If you want to disable capturing of the context, use the TaskAsyncEnumerableExtensions.ConfigureAwait extension method. For more information about synchronization contexts and capturing the current context, see Consuming the Task-based asynchronous pattern. For more information about asynchronous streams, see the Asynchronous streams section of the What's new in C# 8.0 article. 💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes

​​Foreach Loop in C# (part 3) As mentioned before, the foreach loop can be used to iterate any class that has implemented the IEnumerable interface. The following example demonstrates how to implement the IEnumerable interface in order to use the foreach loop with the custom class. Above, the Shop class has implemented the IEnumerable interface that contains the GetEnumerator() method. This will enable the Shop class to be used with the foreach loop that returns the Customer objects.

​​Устали заливать медленный код серверами? Приходите на новый сезон онлайн-конференции для backend-разработчиков Podlodka Backend Crew!  Стартуем 18 июля, тема сезона – "Делаем приложения быстрее"! Всю неделю будем пристально смотреть на производительность приложений. Будем учиться ⚡️Замерять и анализировать нагрузку ⚡️Оптимизировать узкие места, не переписывая сервис с нуля ⚡️Грамотно использовать многопоточность и эффективно утилизировать доступные ресурсы ⚡️Ускорять все, что тормозит! Будем разбираться фундаментально, поэтому привязки к конкретному стеку и фреймворкам в программе не будет. Зато, например, будем разбираться с реактивным подходом и акторной моделью. Как всегда в Podlodka Crew все это на протяжении недели с необычными нескучными форматами сессий, и с живым комьюнити в Slack. До следующего понедельник действует early-bird скидка, а билеты и подробности уже доступны на сайте. Ждем на борту!

​​Foreach Loop in C# (part 2) Important Points: 🔸 The foreach loop iterate only in forward direction. 🔸 Performance wise foreach loop takes much time as compared with for loop. 🔸 Because internally it uses extra memory space as well as. 🔸 The foreach loop use GetEnumarator() method of the IEnumerable interface. So, the foreach loop can be used with any class that has implemented the interface. 🔸 Exit the foreach loop by using break, return, Goto and throw. The following example demonstrates the foreach loop on a dictionary collection.

Foreach Loop in C# (part 1) In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dict
+1
Foreach Loop in C# (part 1) In C#, the foreach loop iterates collection types such as Array, ArrayList, List, Hashtable, Dictionary, etc. It can be used with any type that implements the IEnumerable interface. The following examples demonstrates iteration of an array and a list collection using a foreach loop. The System.Collections.Generic namespace contains the ForEach() extension method that can be used with any built-in collection classes such as List, Dictionary, SortedList, etc.

Will the following code compile?
Anonymous voting

photo content

​​Solutions to Prevent IndexOutOfRangeException (part 3) Solution 2: Use the try catch blocks to catch the IndexOutOfRangeException. In the above example, the entire code wrapped inside the try block may throw errors. The catch block has the Exception filter that can catch any exceptions. So, when the arr[5] statement inside the try block throws an exception, the catch block captures the IndexOutOfRange exception and displays an error message, and continues the execution. 💬 If you appreciate this channel and want it to grow, why not support it: https://www.patreon.com/csharp1001notes

​​Solutions to Prevent IndexOutOfRangeException (part 2) Solution 1: Get the total number of elements in a collection and then check the upper bound of a collection is one less than its number of elements. The following example shows how to fix IndexOutOfRange exception: