Parse чисел в C#
Каждый числовый тип в C# содержит метод
Однако, важно отметить, что результат выполнения этого метода может обернуться для нас и следующими исключениями:
🔸 FormatException:
В этом примере мы пробуем привести (распарсить) дробное значение к типу
🔸 OverflowException:
В данном случае мы пытаемся привести отрицательное число к типу
💬 Одним из полезных атрибутов, помогающем как в документации, так и в контроле поведения, является
#strings
Каждый числовый тип в C# содержит метод
Parse
, с помощью которого мы можем преобразовывать строки в соответствующие числовые значения:byte b1 = byte.Parse("200");
sbyte sb1 = sbyte.Parse("-100");
float f1 = float.Parse("1.2e-4");
Однако, важно отметить, что результат выполнения этого метода может обернуться для нас и следующими исключениями:
🔸 FormatException:
int n1 = int.Parse("3.4"); // FormatException
В этом примере мы пробуем привести (распарсить) дробное значение к типу
int
, в результате чего получаем исключение о некорректности формата входного параметра 3.4
.🔸 OverflowException:
uint ui1 = uint.Parse("-1"); // OverflowException
В данном случае мы пытаемся привести отрицательное число к типу
uint
, значения которого могут быть только положительными. Как итог - исключение, сигнализирующее о переполнении.💬 Одним из полезных атрибутов, помогающем как в документации, так и в контроле поведения, является
ObsoleteAttribute
. С его помощью мы можем помечать элементы программы, которые больше не должны использоваться и вскоре могут быть удалены. Обычно мы получаем предупреждение, однако, знали ли вы, что это поведение настраиваемое и мы можем даже возвращать полноценную ошибку компиляции 🙂?#strings
❇️ Рабочая неделя заканчивается, а значит пришло время очередной недельной подборки на выходные.
Предлагаю вашему внимаю самые 🔥 интересные статьи и вопросы этой недели:
🔸 Why does Enumerable.Single() iterate all elements, even when more than one item has already been found?
🔸 How to use Factory Method Design Pattern in C#
🔸 C# Intermediate – Delegates in C#
🔸 How to properly implement an interface that was designed for async usage?
🔸 Secure Random Integers in .NET Core 3
🔸 .NET Standard vs. .NET Core
Всем отличных выходных 😉
#sof_weekly
Предлагаю вашему внимаю самые 🔥 интересные статьи и вопросы этой недели:
🔸 Why does Enumerable.Single() iterate all elements, even when more than one item has already been found?
🔸 How to use Factory Method Design Pattern in C#
🔸 C# Intermediate – Delegates in C#
🔸 How to properly implement an interface that was designed for async usage?
🔸 Secure Random Integers in .NET Core 3
🔸 .NET Standard vs. .NET Core
Всем отличных выходных 😉
#sof_weekly
Конкатена́ция строк в C#
В C# мы можем использовать оператор
Мы можем использовать этот оператор неограниченное количество раз в рамках одного выражения (expression), а само выражение использовать в тех местах кода, где ожидается строка:
Более того, специальные методы String.Concat и String.Format содержат дополнительные перегрузки, которые также могут быть использованы для конкатенации:
💬 Продолжая рассказывать про полезные фичи в C# нельзя не упомянуть coalesce оператор
#strings
В C# мы можем использовать оператор
+
не только для сложения чисел, но и склеивания (конкатенации) строк:string s1 = "C#";
string s2 = "fun";
string s3 = s1 + " is " + s2; // "C# is fun"
Мы можем использовать этот оператор неограниченное количество раз в рамках одного выражения (expression), а само выражение использовать в тех местах кода, где ожидается строка:
string s1 = "Hello " + " Wor" + "ld";
Console.WriteLine("Wish " + "you " + "the best");
Более того, специальные методы String.Concat и String.Format содержат дополнительные перегрузки, которые также могут быть использованы для конкатенации:
// Concat method
string s4 = String.Concat(new object[] {
"The ", 3, " musketeers"
});
string s5 = String.Concat("This", "That");
// Use String.Format to concatenate
string s6 = string.Format("{0}{1}{2}", s1, " is ", s2);
💬 Продолжая рассказывать про полезные фичи в C# нельзя не упомянуть coalesce оператор
??
. Принцип его работы прост- возвращать left-hand операнд если он не null
и right-hand в обратном случае: int y = x ?? -1
. Берите на вооружение 😉#strings
Forwarded from SeasonedDev
Dear friend,
If you read this, then you, like me, are clearly passionate about programming and tech 💻
My name is Maxim and I'm happy to meet you here ✌️
I hope that what I post on this channel will take your software development skills to the next level.
💬 If you have any questions, then you can always contact me via the @webdev_en chat.
See you at the new channel: @seasoneddev
If you read this, then you, like me, are clearly passionate about programming and tech 💻
My name is Maxim and I'm happy to meet you here ✌️
I hope that what I post on this channel will take your software development skills to the next level.
💬 If you have any questions, then you can always contact me via the @webdev_en chat.
See you at the new channel: @seasoneddev
What will be the output of the following program?
Anonymous Quiz
41%
Error occurred!
47%
Index error occurred!
12%
Compile-time error
#post
.NET 6 is on the way, and I wanted to share some of my favorite new APIs in .NET and ASP.NET Core that you are going to love. Why are you going to love them? Well because they were directly driven by our fantastic .NET developer community! Let’s get started!
Read more...
.NET 6 is on the way, and I wanted to share some of my favorite new APIs in .NET and ASP.NET Core that you are going to love. Why are you going to love them? Well because they were directly driven by our fantastic .NET developer community! Let’s get started!
Read more...
#book
Beginning C# and .NET, 2021 Edition
Perkins Benjamin, Reid Jon D.
Get a running start to learning C# programming with this fun and easy-to-read guide.
As one of the most versatile and powerful programming languages around, you might think C# would be an intimidating language to learn. It doesn't have to be!
Download the book
Beginning C# and .NET, 2021 Edition
Perkins Benjamin, Reid Jon D.
Get a running start to learning C# programming with this fun and easy-to-read guide.
As one of the most versatile and powerful programming languages around, you might think C# would be an intimidating language to learn. It doesn't have to be!
Download the book
Which of the following is the default access modifier of the class members?
Anonymous Quiz
18%
Public
57%
Private
22%
Internal
3%
Protected internal
What will be the output of the following program?
Anonymous Quiz
37%
True
53%
False
7%
Exception
3%
null
#post
For .NET 6, we have made FileStream much faster and more reliable, thanks to an almost entire re-write. For same cases, the async implementation is now a few times faster!
Read more...
For .NET 6, we have made FileStream much faster and more reliable, thanks to an almost entire re-write. For same cases, the async implementation is now a few times faster!
Read more...
#challenge
💻 Array of Multiples | #easy
Create a function that takes two numbers as arguments (
Examples:
🏆 Leave your solutions in the comments. The solution will be posted below in a couple of hours 👇
#interview
💻 Array of Multiples | #easy
Create a function that takes two numbers as arguments (
num
, length
) and returns an array of multiples of num
until the array length reaches length
.Examples:
ArrayOfMultiples(7, 5) ➞ [7, 14, 21, 28, 35]For your convenience: dotnetfiddle.
ArrayOfMultiples(12, 10) ➞ [12, 24, 36, 48, 60, 72, 84, 96, 108, 120]
ArrayOfMultiples(17, 6) ➞ [17, 34, 51, 68, 85, 102]
🏆 Leave your solutions in the comments. The solution will be posted below in a couple of hours 👇
#interview
✨ Here is a solution for the #challenge above
💬 Personally, I like the first solution more, it is much more expressive!
💬 Personally, I like the first solution more, it is much more expressive!
Which of the following is a reserved keyword in C#?
Anonymous Quiz
11%
abstract
5%
as
6%
foreach
77%
All of the above
What will be the output of the following program?
Anonymous Quiz
33%
100
3%
0
58%
Compile-time error
6%
Runtime error