473,326 Members | 2,110 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,326 software developers and data experts.

How to get a default instance of built-in type?

Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));

I have tried:

return t.TypeInitializer.Invoke(null);

but it says "Type initializer is not callable."

-mdb
Dec 23 '06 #1
4 6671
If you use generics you can use the default keyword...

Otherwise you can use Reflect to get the default c'tor, if it exists (i.e.
perform a check):
return t.GetConstructor(BindingFlags.Instance
| BindingFlags.Default
| BindingFlags.Public
, null
, Type.EmptyTypes
, null).Invoke(null);

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"Michael Bray" wrote:
Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));

I have tried:

return t.TypeInitializer.Invoke(null);

but it says "Type initializer is not callable."

-mdb
Dec 23 '06 #2
....forgot an example for generics:
public static void GetDefaultValue<T( out T value )
{
value = default(T);
}
// ...
string text;
GetDefaultValue(out text);

Notice you don't have to deal with typeof at all... Keep in mind, that
won't create an instance for reference types--which will be null.

--
Browse http://connect.microsoft.com/VisualStudio/feedback/ and vote.
http://www.peterRitchie.com/blog/
Microsoft MVP, Visual Developer - Visual C#
"Michael Bray" wrote:
Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));

I have tried:

return t.TypeInitializer.Invoke(null);

but it says "Type initializer is not callable."

-mdb
Dec 23 '06 #3
Michael Bray <mbray@makeDIntoDot_ctiusaDcomwrote:
Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));
For reference types, the default value is always null. For value types,
the default value can be obtained by calling the parameterless
constructor which is guaranteed to exist:

static object DefaultValueOfType (Type t)
{
return t.IsValueType ? Activator.CreateInstance(t)
: null;
}

--
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
Dec 24 '06 #4
Peter Ritchie [C# MVP] wrote:
Notice you don't have to deal with typeof at all... Keep in mind, that
won't create an instance for reference types--which will be null.
Maybe new was better than default.

public static T GetDefault<T>() where T : new()
{
return new T();
}

will work for reference types with a no arg constructor.

Arne
Dec 24 '06 #5

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

Similar topics

18
by: Dan Cernat | last post by:
Hi there, A few threads I had a little chat about default values. I am starting this thread because I want to hear more opinions about the default values of function parameters. Some say they...
2
by: AJ | last post by:
Currently I have a server that has two instances of SQL Server that are both heavily used. We are moving the databases that are on the default instance of this server to a new server. Since the...
14
by: ago | last post by:
Is it possible to have a default value associated python objects? I.e. to flag an attribute in such a way that the assignment operator for the object returns the default attribute instead of the...
3
by: seeker52 | last post by:
How can the default functionality built into access by Microsoft be turned off. For instance, when I hit the enter key on a form focus is set to the next tab stop. How can I hit enter and that...
10
by: cj | last post by:
Here's an easy one, I hope. How do I make button1, which I put on this form from the toolbox, the default button on the form? I thought it used to be a property in the properties window called...
15
by: Youssef Mesri | last post by:
What is the difference between these two situations: 1- hold a namespace which contains justs some functions: namespace MyNamespace { void foo1(); void foo2(); void foo3(); void foo4();
3
by: AMP | last post by:
Hello, I am trying to find out the name of the default form and if Im doing this right Form2 ( is startup form, not form 1 ): public class Form2 : System.Windows.Forms.Form { private Form1...
3
by: subramanian100in | last post by:
If we provide any ctor for a class the compiler does not supply the default ctor. However if we do not provide the copy ctor but provide any other ctor, the compiler still supplies the copy ctor....
3
by: POINTS | last post by:
I have a class and I am printing an instance of it: class Complex: def __init__( self, realpart, imagpart = 0 ): self.r = realpart self.i = imagpart def show( self ): print...
1
by: Justin | last post by:
When executing the command : db2fm -D I received the error: Failed to find the default instance. Environment variable $DB2INSTANCE not set properly. What is the best approach from here -...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
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: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.