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

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

admin - @haarrp
加入频道
#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...
#post

In this post, I'd like to have a look into minimal APIs.

With the preview 4, Microsoft simplified the simplest project template to an absolute minimum. Microsoft created this template to make it easier for new developers to start creating small microservices and HTTP APIs.

Read more...
#post

Now, for the final post in this mini-series, let's turn our attention to a feature that was originally scheduled for release in C# 10, but didn't quite make the cut: required properties.

Read more...
📝 What is the difference between continue and break statements in C#?

🔸 using break statement, you can jump out of a loop

🔸 using continue statement, you can jump over one iteration and then resume your loop execution

#post
📝 When to use Finalize vs Dispose?

🔸 The finalizer method is called when your object is garbage collected and you have no guarantee when this will happen (you can force it, but it will hurt performance).

🔸 The Dispose method, on the other hand, is meant to be called by the code that created your class so that you can clean up and release any resources you have acquired (unmanaged data, database connections, file handles, etc) the moment the code is done with your object.

The standard practice is to implement IDisposable and Dispose so that you can use your object in a using statement such as using(var foo = new MyObject()) { }.

And in your finalizer, you call Dispose, just in case the calling code forgot to dispose of you.

#post
📝 What are Property Accessors?

The get and set portions or blocks of a property are called accessors.

These are useful to restrict the accessibility of a property.

🔸 The set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field.

🔸 By the get accessor we can access the value of the private field. A Get accessor specifies that we can access the value of a field publicly.

#post
📝 You have defined a destructor but it never executed. Why?

The runtime environment automatically invokes the destructor of a class to release the resources that are occupied by variables and methods of an object.

However, in C#, programmers cannot control the timing for invoking destructors, as Garbage Collector is only responsible for releasing the resources used by an object.

Garbage Collector automatically gets information about unreferenced objects from .NET's runtime environment and then invokes the Finalize() method.

Although, it is not preferable to force Garbage Collector to perform garbage collection and retrieve all inaccessible memory (programmers can use the Collect() method of the Garbage Collector class to forcefully execute Garbage Collector).

Take notice that the destructor doesn't (and can't) have a public modifier in-front of it, it's sort of an hint that you can't explicitly call the destructor of an object.

#post
📝 What is the difference between a Struct and a Class in C#?

Class and struct both are the user defined data type but have some major difference:

Struct

🔸 The struct is value type in C# and it inherits from System.Value Type.

🔸 Struct is usually used for smaller amounts of data.

🔸 Struct can't be inherited to other type.

🔸 A structure can't be abstract.

Class

🔸 The class is reference type in C# and it inherits from the System.Object Type.

🔸 Classes are usually used for large amounts of data.

🔸 Classes can be inherited to other class.

🔸 A class can be abstract type.

🔸 We can create a default constructor.

#post
All of these interfaces inherit from IEnumerable. That interface basically lets you use the class in a foreach statement (in C#).

🔸 ICollection is the most basic of the interfaces you listed. It's an enumerable interface that supports a Count and that's about it.

🔸 IList is everything that ICollection is, but it also supports adding and removing items, retrieving items by index, etc. It's the most commonly-used interface for "lists of objects".

🔸 IQueryable is an enumerable interface that supports LINQ. You can always create an IQueryable from an IList and use LINQ to Objects, but you also find IQueryable used for deferred execution of SQL statements in LINQ to SQL and LINQ to Entities.

🔸 IDictionary is a different animal in the sense that it is a mapping of unique keys to values. It is also enumerable in that you can enumerate the key/value pairs, but otherwise it serves a different purpose than the others you listed.

#post
📝 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.

#post
📝 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.

#post
📝 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");
}
}
}

#post
📝 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.

#post
This media is not supported in your browser
VIEW IN TELEGRAM
📝 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
This media is not supported in your browser
VIEW IN TELEGRAM
📝 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.

#post
📝 What are the different types of classes in C#?

The
different types of class in C# are:

🔸 Partial class – Allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.

🔸 Sealed class – It is a class which cannot be inherited. To access the members of a sealed class, we need to create the object of the class. It is denoted by the keyword Sealed.

🔸 Abstract class – It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method. It is denoted by the keyword abstract.

🔸 Static class – It is a class which does not allow inheritance. The members of the class are also static. It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.

#post
📝 What is Weak Reference in C#?

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.

Weak references are useful for objects that use a lot of memory, but can be recreated easily if they are reclaimed by garbage collection.

Suppose a tree view in a Windows Forms application displays a complex hierarchical choice of options to the user. If the underlying data is large, keeping the tree in memory is inefficient when the user is involved with something else in the application.

When the user switches away to another part of the application, you can use the WeakReference class to create a weak reference to the tree and destroy all strong references. When the user switches back to the tree, the application attempts to obtain a strong reference to the tree and, if successful, avoids reconstructing the tree.

#post
📝 What is Boxing and Unboxing?

Boxing and Unboxing both are used for type conversion but have some difference:

🔸 Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR is converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.

🔸 Unboxing is also a process which is used to extract the value type from the object or any implemented interface type. Boxing may be done implicitly, but unboxing have to be explicit by code.

The concept of boxing and unboxing underlines the C# unified view of the type system in which a value of any type can be treated as an object.

#post
📝 What is the difference between string and StringBuilder?

String:

🔸 It's an immutable object that hold string value.

🔸 Performance wise string is slow because its' create a new instance to override or change the previous value.

🔸 String belongs to System namespace.

StringBuilder:

🔸 StringBuilder is a mutable object.

🔸 Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.

🔸 StringBuilder belongs to System.Text.Stringbuilder namespace.

#post
📝 What is deep or shallow copy concept in C#?

🔸 Shallow Copy is about copying an object's value type fields into the target object and the object's reference types are copied as references into the target object but not the referenced object itself. It copies the types bit by bit. The result is that both instances are cloned and the original will refer to the same object.

🔸 Deep Copy is used to make a complete deep copy of the internal reference types, for this we need to configure the object returned by MemberwiseClone().

In other words a deep copy occurs when an object is copied along with the objects to which it refers.

#post