John,
You actually don't need to get a constructor, you can just call the
version of CreateInstance that takes just the type, it will create an
instance with the bits zeroed out, like this:
// Get the type.
Type pobjIntType = typeof(int);
// Create an instance.
object pobjInt = Activator.CreateInstance(pobjIntType);
Of course, you only run this code if you have a value type, otherwise,
you just return null (for reference types). The full code I would use is:
public static object GetDefaultValue(Type type)
{
// If type is null, throw an exception.
if (type == null)
// Throw an exception.
throw new ArgumentNullException("type");
// Check to see if the type is a value type.
// If it is not, return null.
if (!type.IsValueType)
// Return null.
return null;
// Create an instance of the value type.
return Activator.CreateInstance(type);
}
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
John Wood said:
If you run GetConstructor on the value type it returns null though...
doesn't look like any of the value types can provide a default constructor.
message news:
[email protected]...
John,
Yes, actually it would. With Guid and DateTime, since they are
structures, they have default constructors, which you can get through
reflection and call through reflection (once you have the type).
With a string, it is not a value type, so the default value for a string
is null, which the algorithm that I detailed in my previous post will return
to you.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Right, but that won't work for Guid, DateTime or String (to name a few).
Isn't there a method somewhere in the framework that just returns the
default value for a given type?
in
message John,
It's actually quite simple. You can use reflection to determine
whether
or not the type derives from ValueType in some way. If it does, then
you
can just use the default constructor to generate a value with the bits
zeroed out. If it does not derive from ValueType, then it is a
reference
type, and the default value is null.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Yes, that may be true -- but, given an arbitrary value type, how
do
I
programmatically retrieve the default value for that type? It can't
just
be
0 bits, because for a string (for example) that won't work.
I'd have hoped that the boxed equivalent of the value type would have
a
constructor, but GetConstructor returns null.
John,
My question is, how can I retrieve the default value for a given
type?
The default is all bits zeroed out, meaning 0 or 0.0 for numeric
types, false for bools and null for reference types.
For value types, you get the default value when using the default
constructor.
double d = new double(); // effectively the same as double d
=
0.0;