Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why IsValueType is false for int property?

Tags:

c#

.net-core

Ciao,

I'm frustrated about this problem, I have created a simple class like following:

public class Classe
{
    public int Intero { get; set; }

    public Int32 Intero32 { get; set; }

    public double Double { get; set; }

    public string Stringa { get; set; }

    public Classe PerReferenza { get; set; }
}

And I've written this extension method with the goal of return default value of a property (referenced type or value type):

public static class TypeExtensions
{
    public static object GetDefaultValue(this Type t)
    {
        if (t.IsValueType)
            return Activator.CreateInstance(t);

        return null;
    }
}

Following my Main method:

static void Main(string[] args)
{
    Classe c = new Classe();

    foreach (var proprietà in c.GetType().GetProperties())
    {
        var predefinito = proprietà.GetType().GetDefaultValue();

        Console.WriteLine($"Default for {proprietà}: {predefinito ?? "NULL"}");
    }

    Console.ReadKey();
}

This is my output:

Default for Int32 Intero: NULL
Default for Int32 Intero32: NULL
Default for Double Double: NULL
Default for System.String Stringa: NULL
Default for ConsoleApp1.Classe PerReferenza: NULL

I can't understand why I obtain alway FALSE for all properties... The expected output is:

Default for Int32 Intero: 0
Default for Int32 Intero32: 0
Default for Double Double: 0
Default for System.String Stringa: ""
Default for ConsoleApp1.Classe PerReferenza: null

Thank you a lot...

like image 816
ilMattion Avatar asked Jan 28 '26 15:01

ilMattion


1 Answers

You mean proprietà.PropertyType.GetDefaultValue(); you're currently asking whether RuntimePropertyInfo is a value-type (which: it isn't).

like image 81
Marc Gravell Avatar answered Jan 30 '26 05:01

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!