Home >Backend Development >C++ >How Can I Programmatically Get the Default Value of Any Type in C#?

How Can I Programmatically Get the Default Value of Any Type in C#?

DDD
DDDOriginal
2025-01-26 10:01:11236browse

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:

  1. Value type:

    • Generate a new instance using the Activator.CreateInstance method, which usually provides a default value for the value type.
  2. Reference type:

    • Just return 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn