473,378 Members | 1,364 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,378 software developers and data experts.

Default value of any type.

For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);

Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !

Nov 14 '07 #1
14 33975
Generics might help, since default(T) will work fine...
If this isn't an option, you can make life a little simpler: only
value-types have a non-null result, and value-types have a default
ctor (kind-of) - so:

object obj = type.IsValueType ?
Activator.CreateInstance(type) :
obj = null;

Note that since it is boxed, for Nullable<Tyou will get null, not an
boxed empty value - which is probably what you want anyway.

Marc
Nov 14 '07 #2
(copy paste glitch - should have read:)

object obj = type.IsValueType ?
Activator.CreateInstance(type) : null;
Nov 14 '07 #3
On Nov 14, 11:00 am, GeezerButler <kurtr...@gmail.comwrote:
For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);

Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !
For value types, you can always use Activator.CreateInstance(someType)
as there's guaranteed to be a parameterless constructor.
For reference types, the default value is always null.

You can tell the difference using Type.IsValueType.

Jon

Nov 14 '07 #4
Thanks a lot guys!

Nov 14 '07 #5
GeezerButler wrote:
For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);

Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !
Basically, there isn't a very nice way. I have an extension method that
does something like (don't have the code on me):

public class Extension
{
public static object GetDefault(this Type type)
{
return
typeof(Extension).GetMethod("GetDefaultImp").MakeG enericMethod(type).Invoke(null,
new Type[0]);
}
public static T GetDefaultImp<T>()
{
return default(T);
}
}

(If you're not using C# 3, you can do that as plain old static utility
methods)

Note that this is fairly slow. If you need to do this lots, you're
better doing it 'properly' (checking to see if you've got a value or
reference type and returning Activator.CreateInstance(type) or null.

Alun Harford
Nov 14 '07 #6
Alun Harford <de*****@alunharford.co.ukwrote:

<snip>
Note that this is fairly slow. If you need to do this lots, you're
better doing it 'properly' (checking to see if you've got a value or
reference type and returning Activator.CreateInstance(type) or null.
Given that the "proper" way is only about 4 lines of code, what's the
advantage of using the MakeGenericMethod way?

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 14 '07 #7
Note that this is fairly slow. If you need to do this lots, you're better
doing it 'properly' (checking to see if you've got a value or reference
type and returning Activator.CreateInstance(type) or null.
If you're going to do this lots, construct an appropriate delegate "delegate
object ObjectReturnerDelegate()" from the MethodInfo or ConstructorInfo and
cache this in a Dictionary<Type,ObjectReturnerDelegate>

A delegate call is much faster than reflection.
>
Alun Harford

Nov 15 '07 #8
Ben Voigt [C++ MVP] <rb*@nospam.nospamwrote:
Note that this is fairly slow. If you need to do this lots, you're better
doing it 'properly' (checking to see if you've got a value or reference
type and returning Activator.CreateInstance(type) or null.

If you're going to do this lots, construct an appropriate delegate "delegate
object ObjectReturnerDelegate()" from the MethodInfo or ConstructorInfo and
cache this in a Dictionary<Type,ObjectReturnerDelegate>

A delegate call is much faster than reflection.
Except that you've got to use reflection to *get* the method call in
the first place. Rather than caching a delegate, it makes more sense
(IMO) to cache the actual value - and only for value types, at that:

// Thread-safety not shown here
static readonly Dictionary<Type,objectcache =
new Dictionary<Type,object>();

static object GetDefaultValue(Type t)
{
if (!t.IsValueType)
{
return null;
}
object ret;
if (cache.TryGetValue(t, out ret))
{
return ret;
}
ret = Activator.CreateInstance(t);
cache[t] = ret;
return t;
}

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '07 #9
Jon Skeet [C# MVP] wrote:
Alun Harford <de*****@alunharford.co.ukwrote:

<snip>
>Note that this is fairly slow. If you need to do this lots, you're
better doing it 'properly' (checking to see if you've got a value or
reference type and returning Activator.CreateInstance(type) or null.

Given that the "proper" way is only about 4 lines of code, what's the
advantage of using the MakeGenericMethod way?
It's clearer, in my opinion.

Alun Harford
Nov 15 '07 #10
Ben Voigt [C++ MVP] wrote:
>Note that this is fairly slow. If you need to do this lots, you're better
doing it 'properly' (checking to see if you've got a value or reference
type and returning Activator.CreateInstance(type) or null.

If you're going to do this lots, construct an appropriate delegate "delegate
object ObjectReturnerDelegate()" from the MethodInfo or ConstructorInfo and
cache this in a Dictionary<Type,ObjectReturnerDelegate>

A delegate call is much faster than reflection.
If you're doing this lots, your design and/or choice of language is
probably very poor.

Alun Harford
Nov 15 '07 #11
Alun Harford <de*****@alunharford.co.ukwrote:
Given that the "proper" way is only about 4 lines of code, what's the
advantage of using the MakeGenericMethod way?

It's clearer, in my opinion.
Anyone reading that code has to understand generic methods and
accessing generic methods via reflection. With the simple
Activator.CreateInstance all you need to know is what CreateInstance
does (and that's reasonably common) and that all value types have a
parameterless constructor.

I certainly think CreateInstance is clearer and simpler. It's all a
matter of opinion though, yes.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '07 #12
Jon Skeet [C# MVP] wrote:
Alun Harford <de*****@alunharford.co.ukwrote:
>>Given that the "proper" way is only about 4 lines of code, what's the
advantage of using the MakeGenericMethod way?
It's clearer, in my opinion.

Anyone reading that code has to understand generic methods and
accessing generic methods via reflection.
Except for by reflection, I can't think of many times you get an object
and don't know if it's a value type or a reference type.

The only other situation I can think of is interfacing with legacy
pre-generics code. Eugh! :-)

Alun Harford
Nov 15 '07 #13
Alun Harford <de*****@alunharford.co.ukwrote:
Anyone reading that code has to understand generic methods and
accessing generic methods via reflection.

Except for by reflection, I can't think of many times you get an object
and don't know if it's a value type or a reference type.
Absolutely - but when generics and reflection mix, life gets pretty
nasty in my experience. I'd rather avoid that wherever possible.

Another benefit is that the Activator.CreateInstance version works in
..NET 1.1 as well :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 15 '07 #14

"Jon Skeet [C# MVP]" <sk***@pobox.comwrote in message
news:MP*********************@msnews.microsoft.com. ..
Ben Voigt [C++ MVP] <rb*@nospam.nospamwrote:
Note that this is fairly slow. If you need to do this lots, you're
better
doing it 'properly' (checking to see if you've got a value or reference
type and returning Activator.CreateInstance(type) or null.

If you're going to do this lots, construct an appropriate delegate
"delegate
object ObjectReturnerDelegate()" from the MethodInfo or ConstructorInfo
and
cache this in a Dictionary<Type,ObjectReturnerDelegate>

A delegate call is much faster than reflection.

Except that you've got to use reflection to *get* the method call in
the first place. Rather than caching a delegate, it makes more sense
(IMO) to cache the actual value - and only for value types, at that:
Yes, I'm stupid :) Thanks for pointing out the obvious.

For cases other than the default constructor of a value type.... do what I
said.
Nov 15 '07 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: David Lozzi | last post by:
OK simple question. Whats the default value for an string() array? sub LoadStuff(byval one as integer, byval two as string, optional byval three() as string = ??) Its driving me nuts! ...
21
by: planetthoughtful | last post by:
Hi All, As always, my posts come with a 'Warning: Newbie lies ahead!' disclaimer... I'm wondering if it's possible, using raw_input(), to provide a 'default' value with the prompt? I would...
7
by: Justin | last post by:
Is there any way to prevent VB.net to give default value to a variable (changing settings what not...)? For example Dim test As Integer test = test + 1 the statement "test = test + 1"...
4
by: veerleverbr | last post by:
Suppose having define an enum like this: public enum SomeEnum { Something, SomethingElse }
9
by: Eric | last post by:
Hi Everyone, I'm writing a UserControl that exposes a property of the type System.Drawing.Image, like this: Public Property DefaultImage() As Image Get Return propDefaultImage End Get...
4
by: Macneed | last post by:
i am a newbie, i remember i read a book talking about when u declare a array variable using float ABC = new float; the whole array element in ABC ( ABC to ABC ) will automatic initialize to 0...
9
by: puzzlecracker | last post by:
"The C# specification states that all value types have a default parameterless constructor, and it uses the same syntax to call both explicitly declared constructors and the parameterless one,...
5
by: sillyr | last post by:
Hi- I'm using Access 2007. I wanted to change a default value for a field that previously had no default value. I though it would be easy- just set the default value setting to the number t hat I...
1
by: bullfrog83 | last post by:
I have a form with two textboxes: txtSortOrder and txtCourse. I want the txtSortOrder's default value to increment by 10 for each new record (this is to save data entry time). So, if I type in 10 for...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.