How to find the default value of primitive data type at runtime

G

Guest

If I am woring with Generics I can do default(T) to find the default value,
but I can't do default(this.myobj.GetType()).

How do I find the default value?

I >>> DO NOT <<< want to do something like the following...

public object GetDefaultValue( object o )
{
if ( o.GetType() == typeof (bool)
return ( false );
else ( o.GetType() == typeof (int)
return ( 0 );
}
 
G

Guest

If it's a value type, it's always 0 (zero).

If it's a reference type, it's hard to tell. If the reference type has a
comparison/equality operator/interface then you can simply compare it to an
instance created with the default c'tor. Otherwise, you wouldn't be able to
compare it to a "default" value anyway. The default comparison of reference
objects is to compare the reference (e.g. the pointer) not the value.
 
G

Guest

As in my example, how would I go about getting the default constructor in
order to do the comparison against?

Thanks,
Dave
 
G

Guest

Brad Wilson's "Reflection Demystified" includes a sample of getting the
default c'tor:
ConstructorInfo ci = type.GetConstructor(Type.EmptyTypes);

Keep in mind, in order to compare an object to it's "default" it's more
involved than simply getting the default/parameter-less constructor.
Object.Equals is defined as comparing references, not the "value" of an
instance. Just because a type might override Object.Equals, doesn't mean
it's doing anything more than a reference comparison (there's no need to
override Object.Equals if you're not; but that's beside the point).

If the type doesn't override Object.Equals you could try seeing if it
implements various equality/comparison interfaces: IEquatable, IComparable.
If a type is considered "sortable" it would implement IComparable; but that
type may not have a concept of "equality", just less-than or greater-than.
So, you can't fully rely on IComparable for testing equality (i.e. I no way
to tell if an implementation if IComparable is used only for sorting or
sorting AND equality). Start with IEquatable, falling back to IComparable,
if needed.

This, of course, presupposes the type a) has a concept of equality, and b)
has a concept of a "default" value. A class that initializes with the
current date/time, for example, will not have a default value. Or, a class
that defaults to other information unique to an invocation won't have a
default value consistent between invocations (e.g. really important across
remoting boundaries).

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top