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.
Foreach Loop in C# (part 3)
As mentioned before, the foreach loop can be used to iterate any class that has implemented the
Above, the
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.Foreach Loop in C# (part 4)
Beginning with C# 8.0, you can use the
You can also use the
🔸 A type has the public parameterless
🔸 The return type of the
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
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
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,
An enum can be looped through using
The following example gets the names of an enum using the
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.How to loop through an enum in C#? (part 2)
The
The following example shows how to get the values of an enum using the
💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
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
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
In the above example, a
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
.Solutions to fix the NullReferenceException (part 2)
To prevent the
Solution 1: Check whether an object contains a null value or not using an if condition, as shown below:
In the above example,
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.Solutions to fix the NullReferenceException (part 3)
In .NET 5, use the null conditional operator
In the above example,
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 4)
In .NET 4.x and above versions, use Null-Coalescing operator
In the above example,
💬 Like this note? Want to support the channel? Become a patron: https://www.patreon.com/csharp1001notes
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
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
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.