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.Generate Random Numbers in Range
Use the
The following example generates the positive random numbers that are less than 10.
Use the
Next(int)
method overload to generate a random integer that is less than the specified maximum value.The following example generates the positive random numbers that are less than 10.
Generate Random Number in Min to Max Range
Use the
In the above example,
Use the
Next(int min, int max)
overload method to get a random integer that is within a specified range.In the above example,
rnd.Next(10, 20)
generate random numbers that will be between 10 to 19.Generate Random Floating Point Number
Use the
Use the
NextDouble()
method to get a random floating-point number between 0.0 to 1.0, as shown below.Seed Value
The
Two different instances of the
In the above example, two different objects of the Random class are instantiated with the same seed value. So, they will generate the same random numbers.
By default, the seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.
💬 If you appreciate this channel and want it to grow, why not support it: https://www.patreon.com/csharp1001notes
The
Random
class uses the seed value as a starting value for the pseudo-random number generation algorithm. By default, the Random
class uses the system clock to generate its seed value so that each instance of the Random
class can generate different random numbers.Two different instances of the
Random
class having the same seed value will generate the same random numbers, as shown below.In the above example, two different objects of the Random class are instantiated with the same seed value. So, they will generate the same random numbers.
By default, the seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator.
💬 If you appreciate this channel and want it to grow, why not support it: https://www.patreon.com/csharp1001notes
Default Value of Auto-Implemented Property
In C# 6.0 or higher versions, assign the inline default value to the auto-implemented property, as shown below.
In C# 6.0 or higher versions, assign the inline default value to the auto-implemented property, as shown below.
Using DefaultValue Attribute
You can assign the default value using the DefaultValueAttribute attribute, as shown below.
💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes
You can assign the default value using the DefaultValueAttribute attribute, as shown below.
💬 Support the channel and its mission to help programmers learn C#: https://www.patreon.com/csharp1001notes
In C#, the Scope of the variable determines the accessibility of the variable to a particular part of the application. Variables can be declared within the class, method, and code block of a loop, condition, etc.
There are three types of scopes in C#.
- Class Level Scope
- Method Level Scope
- Code-Block Level Scope
Class Level Scope
A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.
In the above example, the
The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.
There are three types of scopes in C#.
- Class Level Scope
- Method Level Scope
- Code-Block Level Scope
Class Level Scope
A variable declared within a class is known as a field. It has a class-level scope that can be accessed anywhere in the class, such as class methods, properties, etc.
In the above example, the
Student
class contains two class variables (a.k.a. fields) _firstName
and _lastName
. These fields can be accessed anywhere within the class, i.e., within any non-static methods and properties.The class level variables can also be accessed out of class using class objects depending on the access modifiers. The static variables of the class can only be accessed from the static methods or properties.
Method Level Scope
A variable declared within a method has a method level Scope. It is also known as a local variable of the method where it is declared. It cannot be accessed outside the method.
Any nested code blocks within the method can access this type of variable. It cannot be declared twice with the same name within the same scope.
The local variable's scope ends when the method execution completes, and they will be collected by the garbage collector.
The following example shows the method Level scope.
In the above example, the
A variable declared within a method has a method level Scope. It is also known as a local variable of the method where it is declared. It cannot be accessed outside the method.
Any nested code blocks within the method can access this type of variable. It cannot be declared twice with the same name within the same scope.
The local variable's scope ends when the method execution completes, and they will be collected by the garbage collector.
The following example shows the method Level scope.
In the above example, the
Main()
method can only access variables declared in the Main()
method but not variables of other methods. In the same way, the Process()
method cannot access variables declared in the Main()
or any other method.Code-Block Level Scope
A variable declared within a loop or any block within brackets has the code-block level scope. A variable declared within a loop or code block cannot be accessed outside of it, whereas a variable declared outside of the loop can be accessible within the loop.
In the above example, a variable
A variable must be declared outside of the code block to make it accessible to outside code.
💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
A variable declared within a loop or any block within brackets has the code-block level scope. A variable declared within a loop or code block cannot be accessed outside of it, whereas a variable declared outside of the loop can be accessible within the loop.
In the above example, a variable
i
declared within a for loop. So, it can only be accessed within the for
loop block and cannot be accessed outside for loop. In the same way, x
is declared within the if block, so it can only be accessed in that block but not outside of it.A variable must be declared outside of the code block to make it accessible to outside code.
💬 The channel has been running since 2018. It needs your support: https://www.patreon.com/csharp1001notes
When to use Struct over Class in C# (part 1)
The Struct is a similar and lighter version of the class in C#. However, there are some pros and cons of Struct. After knowing this, you can understand when to use struct over class in c#.
Limitations of Struct:
🔸 Class is a reference type, whereas Struct is a value type.
🔸 A default constructor or destructor cannot be created in Struct.
🔸 Structs inherit from
🔸 Struct types cannot be abstract and are always sealed implicitly.
🔸 Struct members cannot be abstract, sealed, virtual, or protected.
🔸 Structs copy the entire value on the assignment, whereas reference types copy the reference on assignment. So, large reference type assignments are cheaper than the value types.
🔸 Instance field declarations in Struct cannot include variable initializers. But, static fields in Struct can include variable initializers.
🔸 A null value can be assigned to a struct as it can be used as a nullable type.
🔸 Structs are allocated either on the stack or inline in containing types and deallocated when the stack or the containing type gets deallocated. But, reference types are allocated on the heap and garbage-collected. So, the allocation and deallocation of structs are cheaper than classes.
🔸 Array elements of reference types are references to the instances of the reference types that exist on the heap, whereas array elements of value types are the real instances of the value type. So, allocation and deallocation of value type arrays are much cheaper than the reference type arrays.
🔸 Value types get boxed and unboxed during the typecasting. An excessive amount of boxing and unboxing results in a negative impact on the heap, garbage collector, and the application's performance.
The Struct is a similar and lighter version of the class in C#. However, there are some pros and cons of Struct. After knowing this, you can understand when to use struct over class in c#.
Limitations of Struct:
🔸 Class is a reference type, whereas Struct is a value type.
🔸 A default constructor or destructor cannot be created in Struct.
🔸 Structs inherit from
System.ValueType
, cannot be inherited from another Struct or Class, and cannot be a base class.🔸 Struct types cannot be abstract and are always sealed implicitly.
🔸 Struct members cannot be abstract, sealed, virtual, or protected.
🔸 Structs copy the entire value on the assignment, whereas reference types copy the reference on assignment. So, large reference type assignments are cheaper than the value types.
🔸 Instance field declarations in Struct cannot include variable initializers. But, static fields in Struct can include variable initializers.
🔸 A null value can be assigned to a struct as it can be used as a nullable type.
🔸 Structs are allocated either on the stack or inline in containing types and deallocated when the stack or the containing type gets deallocated. But, reference types are allocated on the heap and garbage-collected. So, the allocation and deallocation of structs are cheaper than classes.
🔸 Array elements of reference types are references to the instances of the reference types that exist on the heap, whereas array elements of value types are the real instances of the value type. So, allocation and deallocation of value type arrays are much cheaper than the reference type arrays.
🔸 Value types get boxed and unboxed during the typecasting. An excessive amount of boxing and unboxing results in a negative impact on the heap, garbage collector, and the application's performance.
When to use Struct over Class in C# (part 2)
Generally, the use of value types will affect fewer objects in the managed heap, less load on the garbage collector, and thus better performance. However, it has a drawback as well. Value types will become expensive in the case of a big Struct. Thus, before using Struct we should understand when to use Struct over Class in C#.
🔸 If all the member fields are value types.
🔸 If instances of the type are small and short-lived or embedded to other instances.
🔸 If it logically denotes a single value, same as primitive types like int, double, etc.
🔸 If the size of the instance is below 16 bytes.
🔸 If it will not be boxed and unboxed again and again
.
🔸 If it is immutable, that means when an instance of a reference type gets changed, it affects all the references indicating the instance. But, in the case of value types, it does not affect any of its copies. For this reason, changes in value types may raise confusion in many users. So, it should be immutable.
Generally, the use of value types will affect fewer objects in the managed heap, less load on the garbage collector, and thus better performance. However, it has a drawback as well. Value types will become expensive in the case of a big Struct. Thus, before using Struct we should understand when to use Struct over Class in C#.
🔸 If all the member fields are value types.
🔸 If instances of the type are small and short-lived or embedded to other instances.
🔸 If it logically denotes a single value, same as primitive types like int, double, etc.
🔸 If the size of the instance is below 16 bytes.
🔸 If it will not be boxed and unboxed again and again
.
🔸 If it is immutable, that means when an instance of a reference type gets changed, it affects all the references indicating the instance. But, in the case of value types, it does not affect any of its copies. For this reason, changes in value types may raise confusion in many users. So, it should be immutable.
Convert int to Enum by Type Casting
You can explicitly type cast an int to a particular enum type, as shown below.
You can explicitly type cast an int to a particular enum type, as shown below.
Convert int to Enum using Enum.ToObject() Method
Use the Enum.ToObject() method to convert integers to enum members, as shown below.
Use the Enum.ToObject() method to convert integers to enum members, as shown below.
Convert an Object to JSON in C#
Here you will learn how to convert C# object to JSON using Serialization.
JSON (Javascript Object Notation) is used for storing and data transfer. It is also used in API calls to exchange the data from API to different web applications or from browser to server and vice versa.
Serialization is the process of storing the state of an object and being able to recreate it when required. The reverse of it is known as Deserialization.
The .NET 5 framework provides the built-in
The .NET 4.x framework does not provide any built-in
Here you will learn how to convert C# object to JSON using Serialization.
JSON (Javascript Object Notation) is used for storing and data transfer. It is also used in API calls to exchange the data from API to different web applications or from browser to server and vice versa.
Serialization is the process of storing the state of an object and being able to recreate it when required. The reverse of it is known as Deserialization.
The .NET 5 framework provides the built-in
JsonSerializer
class in the System.Text.Json
namespace to convert C# objects to JSON and vice-versa.The .NET 4.x framework does not provide any built-in
JsonSerializer
class that converts objects to JSON. You have to install the NuGet package Microsoft.Extensions.Configuration.Json
in your project to include the System.Text.Json.JsonSerializer
to your project which can be used to convert objects to JSON and vice-versa.Convert an Object to a Minified JSON String
The following example shows the conversion of an object to the formatted JSON string:
In the above example, we specified an option with
The following example shows the conversion of an object to the formatted JSON string:
In the above example, we specified an option with
WriteIndented=true
as a parameter in the Serialize()
method. This will return a formatted string with indentation.Convert an Object to a UTF-8 String
Serialization to an utf-8 byte array is a bit faster than the string method. This is because the bytes of utf-8 is not required to convert to strings of utf-16.
The following example shows the conversion of an object to a minified JSON string using
Thus, you can convert C# object to JSON in different ways for different versions using
Serialization to an utf-8 byte array is a bit faster than the string method. This is because the bytes of utf-8 is not required to convert to strings of utf-16.
The following example shows the conversion of an object to a minified JSON string using
JsonSerializer.SerializeToUtf8Bytes
method.Thus, you can convert C# object to JSON in different ways for different versions using
JsonConvert.Serialize()
method in .NET 4.x and .NET 5.