Get System Default Types

C

Champika Nirosh

Hi All,

I have the string value of the System types.. now I need to get the default
value for that system type..

I have string s = "int";

not I need string sd = "0";

sd is the default for the int type..

same way is it is a bool then default value should be "false"

How can I do this..

Nirosh.
 
I

Ian Griffiths [C# MVP]

This does what you described, but probably not what you expect...:

static string GetDefaultValueString(string typeName)
{
Type t = Type.GetType(typeName);
object o = Activator.CreateInstance(t);
return o.ToString();
}

Why do I say it won't do what you expect? Well here's my test code:

Console.WriteLine(GetDefaultValueString("System.Int32"));
Console.WriteLine(GetDefaultValueString("System.Boolean"));

and this prints out:

0
False

Note that I'm using the real names of the types here. You said:
I have string s = "int";

That's not the name of the type. That's the name of an alias C# happens to
use as a shorthand for System.Int32.

The only mechanism I'm aware of for mapping from one of these C# aliases to
the real type name is the C# compiler itself! You could use the codedom to
do this, but it's rather heavyweight - a much simpler solution would just be
to have a hard-coded list for all these types.

Do you really need to use the C#-specific aliases for these system types?

Also, note that the default value of Boolean prints out as "True" not
"true", so again that's not valid C#. So this might not do what you
require. What exactly are you trying to achieve?
 
M

Mattias Sjögren

This does what you described, but probably not what you expect...:

Plus it doesn't work for reference types unless you add something like

if ( !t.IsValueType ) return "null";



Mattias
 

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