0

I am trying to get default value of a property from it's Type.

But I get an error (comment in my code).

Spent quiet some time on this, any help would be appreciated, Thanks.

This is a simplified version of the code.

    public void test<T>(T classObject)
    {
        Type t = typeof(T);

        var properties = t.GetProperties(BindingFlags.Public);


        foreach (var prop in properties)
        {
            var type = prop.GetType();

            var defaultValue = default(type); //Get an error here saying "the type or namespace name "type" could not be found
        }
    }
  • So what I do is, I pass in an object to my method, and get all it's properties, Then i loop through the properties trying to get their default value. – A. S. Adam Oct 06 '17 at 15:45
  • You'd want to do `default(prop.PropertyType)`. Your code has the value of `type` as the `Type` for `PropertyInfo` – DiskJunky Oct 06 '17 at 15:48
  • It does not even recognise "prop" in the default(prop), so I can do default(property.PropertyType) and get the same error... – A. S. Adam Oct 06 '17 at 15:53
  • 1
    You're correct, apologies. Replace `default(prop.PropertyType)` with `Activator.CreateInstance(prop.PropertyType)` – DiskJunky Oct 06 '17 at 15:55
  • Cheers mate ! that worked, was wondering why did'nt the default work... – A. S. Adam Oct 06 '17 at 16:26

0 Answers0