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...