📝 What is scope of a Protected Internal member variable of a C# class?
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
The protected internal access specifier allows a class to hide its member variables and member functions from other class objects and functions, except a child class within the same application. This is also used while implementing inheritance.
Find an invalid example of using C# var
Anonymous Quiz
7%
var a = 3.141592;
74%
var a = null;
11%
var a = db.Stores;
8%
var a = db.Stores.Single(p => p.Id == 1);
❓What does thread pooling mean?
The collection of threads is known as thread pooling. These threads find application when the tasks are to be performed without disturbing the primary threads. To manage the operations of the threads in the pool, System.Threading.ThreadPool namespace is used.
The collection of threads is known as thread pooling. These threads find application when the tasks are to be performed without disturbing the primary threads. To manage the operations of the threads in the pool, System.Threading.ThreadPool namespace is used.
Which of the followings does not allow you to use C# static keyword?
Anonymous Quiz
3%
(Method) static void Run() {}
11%
(Property) static int Prop {get; set;}
6%
(Field) static int _field;
3%
(Class) static class MyClass {}
10%
(Constructor) static MyClass() {}
42%
(Destructor) static ~MyClass() {}
25%
(Event) static event EventHandler evt;
In C#, what is similar to C++ function pointer?
Anonymous Quiz
6%
Event
6%
Interface
77%
Delegate
11%
Method
Asynchronous programming with async, await, Task in C# (part 1)
C# and .NET Framework (4.5 & Core) supports asynchronous programming using some native functions, classes, and reserved keywords.
Before we see what is asynchronous programming, let's understand what is synchronous programming using the following console example.
In the above example, the
The above program executes synchronously. It means execution starts from the
C# and .NET Framework (4.5 & Core) supports asynchronous programming using some native functions, classes, and reserved keywords.
Before we see what is asynchronous programming, let's understand what is synchronous programming using the following console example.
In the above example, the
LongProcess()
method is some long-running task such as reading a file from the server, calling a web API that returns a large amount of data or uploading or downloading a big file. It takes a little longer time to execute (Thread.Sleep(4000)
holds it for 4 seconds just to show long execution time). The ShortProcess()
is a simple method that gets executed after the LongProcess()
method.The above program executes synchronously. It means execution starts from the
Main()
method wherein it first executes the LongProcess()
method and then ShortProcess()
method. During the execution, an application gets blocked and becomes unresponsive (You can see this in Windows-based applications mainly). This is called synchronous programming where execution does not go to next line until the current line executed completely.What is Asynchronous Programming? (part 2)
In asynchronous programming, the code gets executed in a thread without having to wait for an I/O-bound or long-running task to finish. For example, in the asynchronous programming model, the
Microsoft recommends Task-based Asynchronous Pattern to implement asynchronous programming in the .NET Framework or .NET Core applications using async , await keywords and Task or Task<TResult> class.
Now let's rewrite the above example in asynchronous pattern using
In the above example, the
The
Now, the program starts executing from the
In asynchronous programming, the code gets executed in a thread without having to wait for an I/O-bound or long-running task to finish. For example, in the asynchronous programming model, the
LongProcess()
method will be executed in a separate thread from the thread pool, and the main application thread will continue to execute the next statement.Microsoft recommends Task-based Asynchronous Pattern to implement asynchronous programming in the .NET Framework or .NET Core applications using async , await keywords and Task or Task<TResult> class.
Now let's rewrite the above example in asynchronous pattern using
async
keyword.In the above example, the
Main()
method is marked by the async
keyword, and the return type is Task
. The async
keyword marks the method as asynchronous. Note that all the methods in the method chain must be async
in order to implement asynchronous programming. So, the Main()
method must be async
to make child methods asynchronous.The
LongProcess()
method is also marked with the async
keyword which makes it asynchronous. The await Task.Delay(4000);
holds the thread execute for 4 seconds.Now, the program starts executing from the
async Main()
method in the main application thread. The async LongProcess()
method gets executed in a separate thread and the main application thread continues execution of the next statement which calls ShortProcess()
method and does not wait for the LongProcess()
to complete.async, await, and Task (part 3)
Use
The
The Task class represents an asynchronous operation and Task<TResult> generic class represents an operation that can return a value. In the above example, we used
The following demonstrates the
In the above example, in the static
An
Use
async
along with await
and Task
if the async
method returns a value back to the calling code. We used only the async
keyword in the above program to demonstrate the simple asynchronous void method.The
await
keyword waits for the async
method until it returns a value. So the main application thread stops there until it receives a return value.The Task class represents an asynchronous operation and Task<TResult> generic class represents an operation that can return a value. In the above example, we used
await Task.Delay(4000)
that started async
operation that sleeps for 4 seconds and await holds a thread until 4 seconds.The following demonstrates the
async
method that returns a value.In the above example, in the static
async Task<int> LongProcess()
method, Task<int>
is used to indicate the return value type int. int val = await result;
will stop the main thread there until it gets the return value populated in the result. Once get the value in the result
variable, it then automatically assigns an integer to val
.An
async
method should return void
, Task
, or Task<TResult>
, where TResult
is the return type of the async
method. Returning void
is normally used for event handlers. The async
keyword allows us to use the await keyword within the method so that we can wait for the asynchronous method to complete for other methods which are dependent on the return value.async, await, and Task (part 4)
If you have multiple
In the above program, we do await result1 and await result2 just before we need to pass the return value to another method.
Thus, you can use
💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
If you have multiple
async
methods that return the values then you can use await
for all methods just before you want to use the return value in further steps.In the above program, we do await result1 and await result2 just before we need to pass the return value to another method.
Thus, you can use
async
, await, and Task to implement asynchronous programming in .NET Framework or .NET Core using C#.💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
Difference between static, readonly, and constant in C# (part 1)
static:
🔸 Declared using the
🔸 Classes, constructors, methods, variables, properties, event and operators can be static. The struct, indexers, enum, destructors, or finalizers cannot be static.
🔸 Static members can only be accessed within the static methods. The non-static methods cannot access static members.
🔸 Value of the static members can be modified using
🔸 Static members can be accessed using
static:
🔸 Declared using the
static
keyword.🔸 Classes, constructors, methods, variables, properties, event and operators can be static. The struct, indexers, enum, destructors, or finalizers cannot be static.
🔸 Static members can only be accessed within the static methods. The non-static methods cannot access static members.
🔸 Value of the static members can be modified using
ClassName.StaticMemberName
.🔸 Static members can be accessed using
ClassName.StaticMemberName
, but cannot be accessed using object.Difference between static, readonly, and constant in C# (part 2)
readonly:
🔸 Declared using the
🔸 Only the class level fields can be readonly. The local variables of methods cannot be readonly.
🔸 Readonly fields can be initialized at declaration or in the constructor. Therefore, readonly variables are used for the run-time constants.
🔸 Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor.
🔸 Readonly members can be accessed using object, but not
readonly:
🔸 Declared using the
readonly
keyword.🔸 Only the class level fields can be readonly. The local variables of methods cannot be readonly.
🔸 Readonly fields can be initialized at declaration or in the constructor. Therefore, readonly variables are used for the run-time constants.
🔸 Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor.
🔸 Readonly members can be accessed using object, but not
ClassName.ReadOnlyVariableName
.Difference between static, readonly, and constant in C# (part 3)
const:
🔸 Declared using the
🔸 Only the class level fields or variables can be constant.
🔸 The constant fields must be initialized at the time of declaration. Therefore, const variables are used for compile-time constants.
🔸 Constant variables cannot be modified after declaration.
🔸 Const members can be accessed using
const:
🔸 Declared using the
const
keyword. By default a const is static that cannot be changed.🔸 Only the class level fields or variables can be constant.
🔸 The constant fields must be initialized at the time of declaration. Therefore, const variables are used for compile-time constants.
🔸 Constant variables cannot be modified after declaration.
🔸 Const members can be accessed using
ClassName.ConstVariableName
, but cannot be accessed using object.Difference between static, readonly, and constant in C# (part 4)
The following example demonstrates the difference between static, readonly, and const variables.
💬 Like this note? Want to support the channel? Become a patron: https://www.patreon.com/csharp1001notes
The following example demonstrates the difference between static, readonly, and const variables.
💬 Like this note? Want to support the channel? Become a patron: https://www.patreon.com/csharp1001notes
IndexOutOfRangeException in C# (part 1)
The
The following example throws the
In the above example, an
The
IndexOutOfRangeException
is an exception that will be thrown while accessing an element of a collection with an index that is outside of its range. It occurs when an invalid index is used to access a member of a collection.The following example throws the
IndexOutOfRange
exception:In the above example, an
arr
contains five elements. It will throw an IndexOutOfRange
exception when trying to access value more than its total elements. Above, trying to access the 6th element using arr[5]
will throw IndexOutOfRange
exception.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
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:Solutions to Prevent IndexOutOfRangeException (part 3)
Solution 2: Use the try catch blocks to catch the
In the above example, the entire code wrapped inside the try block may throw errors. The catch block has the
💬 If you appreciate this channel and want it to grow, why not support it: https://www.patreon.com/csharp1001notes
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
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
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.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
🔸 Exit the foreach loop by using break, return, Goto and throw.
The following example demonstrates the foreach loop on a dictionary collection.
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.