2

I need to get names of few objects. The names cannot contain their bits (16/32/64). Actaully I do it this way object.GetType().Name. When I use int as object (int.GetType().Name) it returns int. But when I use uint it returns uint32. I want to get only uint. Is there a better way to do this than String.Replace?

v0id
  • 151
  • 1
  • 12
  • Why exactly do you want `unit` rather than `uint32`? What are you trying to achieve? – Rob Jan 28 '17 at 14:10
  • 1
    Hmm, no, you won't get "int". Do try to make a minimal effort to post valid repro code. Words like `int` and `uint` are *keywords* in the C# language. Translating from the framework type name to the keyword is probably best done with a switch statement. Or just don't bother since it doesn't matter. – Hans Passant Jan 28 '17 at 14:12
  • possible duplicate of [Is there a way to get a type's alias through reflection?](http://stackoverflow.com/a/1363309/2803565) – S.Serpooshan Jan 28 '17 at 14:34
  • Possible duplicate of [Telerik Radgrid GridDataItem.DataItem is empty when updating (OnUpdateCommand handler)](http://stackoverflow.com/questions/2803565/telerik-radgrid-griddataitem-dataitem-is-empty-when-updating-onupdatecommand-ha) – jjj Jan 28 '17 at 14:48

1 Answers1

6

You can use the compiler services to do so:

static string GetFriendlyTypeName<T>()
{
    var csharpCodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
    var codeType = new System.CodeDom.CodeTypeReference(typeof(T));
    return csharpCodeProvider.GetTypeOutput(codeType);
}

static void Main(string[] args)
{
    Console.WriteLine(GetFriendlyTypeName<Int32>()); //int
    Console.WriteLine(GetFriendlyTypeName<UInt32>()); //uint
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
Zein Makki
  • 29,485
  • 6
  • 52
  • 63