C# 1001 notes
Open in Telegram
Регулярные короткие заметки по C# и .NET. Просто о сложном для каждого. admin - @haarrp
Show more6 538
Subscribers
-124 hours
-97 days
-230 days
Posts Archive
6 538
#challenge
💻 Pentagonal Number | #easy
Write a function that takes a positive integer num and calculates how many dots exist in a pentagonal shape around the center dot on the Nth iteration.
In the image below you can see the first iteration is only a single dot. On the second, there are 6 dots. On the third, there are 16 dots, and on the fourth there are 31 dots.
Return the number of dots that exist in the whole pentagon on the Nth iteration.
Examples:
pentagonal(1) ➞ 1
pentagonal(2) ➞ 6
pentagonal(3) ➞ 16
pentagonal(8) ➞ 141
🏆 Leave your solutions in the comments. The solution will be posted below in a couple of hours 👇
#interview6 538
📝 What are the benefits of a Deferred Execution in LINQ?
In LINQ, queries have two different behaviors of execution: immediate and deferred.
Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. It greatly improves performance by avoiding unnecessary execution.
Consider:
results = collection
.Select(item => item.Foo)
.Where(foo => foo < 3)
.ToList();
With deferred execution, the above iterates your collection one time, and each time an item is requested during the iteration, performs the map operation, filters, then uses the results to build the list.
If you were to make LINQ fully execute each time, each operation (Select / Where) would have to iterate through the entire sequence. This would make chained operations very inefficient.
#post6 538
📝 How we can pass parameters to a method?
There are three ways that parameters can be passed to a method:
🔸 Value parameters − This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
🔸 Reference parameters − This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
🔸 Output parameters − This method helps in returning more than one value.
#post
6 538
#challenge
💻 Letter Distance | #easy
Given two words, the letter distance is calculated by taking the absolute value of the difference in character codes and summing up the difference.
If one word is longer than another, add the difference in lengths towards the score.
To illustrate:
"fly") = dist("h", "f") + dist("o", "l") + dist("u", "y") + dist(house.Length, fly.Length)
= |104 - 102| + |111 - 108| + |117 - 121| + |5 - 3|
= 2 + 3 + 4 + 2
= 11
Examples:
LetterDistance("sharp", "sharq") ➞ 1
LetterDistance("abcde", "Abcde") ➞ 32
LetterDistance("abcde", "bcdef") ➞ 5
🏆 Leave your solutions in the comments. The solution will be posted below in a couple of hours 👇
#interview6 538
📝 How can we check equality in .NET?
🔸 The
ReferenceEquals() method - checks if two reference type variables(classes, not structs) are referred to the same memory address.
🔸 The virtual Equals() method. (System.Object) - checks if two objects are equivalent.
🔸 The static Equals() method - is used to handle problems when there is a null value in the check.
🔸 The Equals method from IEquatable interface.
🔸 The comparison operator == - usually means the same as ReferenceEquals, it checks if two variables point to the same memory address. The gotcha is that this operator can be override to perform other types of checks. In strings, for instance, it checks if two different instances are equivalent.
#post6 538
📝 What is namespace in C#?
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
🔸 NET uses namespaces to organize its many classes.
🔸 Declaring your own namespaces can help you control the scope of class and method names in larger programming projects.
SampleNamespace
{
class SampleClass
{
public void SampleMethod()
{
System.Console.WriteLine(
"SampleMethod inside SampleNamespace");
}
}
}
#post6 538
#challenge
💻 Compounding Letters | #easy
Create a function that takes a string and returns a new string with each new character accumulating by +1. Separate each set with a dash.
Capitalize the first letter of each set.
Examples:
Accum("abcd") ➞ "A-Bb-Ccc-Dddd"
Accum("RqaEzty") ➞ "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
Accum("cwAt") ➞ "C-Ww-Aaa-Tttt"
🏆 Leave your solutions in the comments. The solution will be posted below in a couple of hours 👇
#interview6 538
📝 How to implement the Where method in C#?
The
yield keyword actually does quite a lot here. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
The function returns an object that implements the IEnumerable<T> interface. If a calling function starts foreaching over this object, the function is called again until it "yields" result based on some predicate.
This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.
#post6 538
📝 What is an Abstract Class?
The
abstract modifier indicates that the thing being modified has a missing or incomplete implementation. The abstract modifier can be used with classes, methods, properties, indexers, and events.
An Abstract class is a class which is denoted by abstract keyword and can be used only as a Base class.
Abstract classes have the following features:
🔸 An abstract class cannot be instantiated.
🔸 An abstract class may contain abstract methods and accessors.
🔸 It is not possible to modify an abstract class with the sealed modifier because the two modifiers have opposite meanings. The sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
🔸 A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.
#post6 538
Вебинар для разработчиков С++, которые хотят использовать последние возможности языка, а также для программистов на других языках, чтобы узнать, какие преимущества даёт разработка на C++.
Максимально кратко и содержательно расскажем о новых фичах Стандарта:
1. зачем они нужны и насколько они круты;
2. когда и для чего их можно будет использовать в своих программах;
3. особое внимание уделим модулям, концептам, диапазонам (Ranges), корутинам и трёхстороннему сравнению;
4. также поговорим и об остальных нововведениях.
25 февраля в 19.30 (Мск)
70 минут обзор + 20 минут ответы на вопросы
👉Бесплатная регистрация на сайте
6 538
Конкатена́ция строк в C#
В 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
Available now! Telegram Research 2025 — the year's key insights 
