Home >Backend Development >C++ >How Can I Programmatically Get the Default Value of Any Type in C#?
Procedural equivalent to default(Type)
When using reflection to iterate over properties of a type and set certain types to their default values, you may want to take a cleaner approach than explicit type-based defaults. In this case, is there a programmatic equivalent to default(Type) that can be used for such scenarios?
Solution:
To achieve this, the following options are available:
Value type:
Activator.CreateInstance
method, which usually provides a default value for the value type. Reference type:
null
since the reference type defaults to null
. Sample code:
The following code example illustrates how to obtain the default value programmatically:
<code class="language-csharp">public static object GetDefault(Type type) { if (type.GetTypeInfo().IsValueType) { return Activator.CreateInstance(type); } return null; }</code>
Note:
In newer .NET versions (e.g., .NET Standard), type.IsValueType
is written as type.GetTypeInfo().IsValueType
.
The above is the detailed content of How Can I Programmatically Get the Default Value of Any Type in C#?. For more information, please follow other related articles on the PHP Chinese website!