2

As WCF does not support Types, I'm passing the type as a string type. For eg:

var str= "int"

Now I want to convert this to a Type int as i want to pass CLR types as parameters.

Is there anyway of achieving this?

Dave New
  • 38,496
  • 59
  • 215
  • 394
Ankit
  • 133
  • 4
  • 16

3 Answers3

3

You mean like using Type.GetType()?

string typeName = "System.Int32"; // Sadly this won't work with just "int"
Type actualType = Type.GetType(typeName);
Rawling
  • 49,248
  • 7
  • 89
  • 127
  • @Rwaling well this is one working way but anyway round with just passing int rather than the whole "system.Int32" – Ankit Jul 19 '12 at 10:50
  • 1
    @Ankit - there are only a limited numer of aliases like this (`int`, `long`, `byte`, `float`, `double`, `decimal`, probably a few more). You could easily set up a `switch` statement to catch all of these, and then use `GetType` to handle real type names. – Rawling Jul 19 '12 at 10:54
  • Thought of it but was just looking for an alternate option. Thnx :) – Ankit Jul 19 '12 at 10:56
2

If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to get the type name qualified by its namespace (see @Rawling answer):

var str = typeof(int).FullName;
// str == "System.Int32" 

Otherwise, you need an assembly-qualified name of the Type:

var str = typeof(int).AssemblyQualifiedName;
// str == "System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"

Then you can use Type.GetType:

var intType = Type.GetType(str);

Edit:

If you want to use the system aliases, you can create a Dictionary<string, Type> to map all of the aliases to their type:

static readonly Dictionary<string, Type> Aliases =
    new Dictionary<string, Type>()
{
    { "byte", typeof(byte) },
    { "sbyte", typeof(sbyte) },
    { "short", typeof(short) },
    { "ushort", typeof(ushort) },
    { "int", typeof(int) },
    { "uint", typeof(uint) },
    { "long", typeof(long) },
    { "ulong", typeof(ulong) },
    { "float", typeof(float) },
    { "double", typeof(double) },
    { "decimal", typeof(decimal) },
    { "object", typeof(object) }
};
Community
  • 1
  • 1
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
0

Try this

 int myInt = 0;
    int.TryParse(str, out myInt);

    if(myInt > 0)
    {
     // do your stuff here
    }

if you mean you only want to sent the type then use

string str = myInt.GetType().ToString(); and it will give you the type

JohnnBlade
  • 4,261
  • 1
  • 21
  • 22