CSharp/C# >> Return type name as string

by Andrus » Fri, 06 Jun 2008 02:04:47 GMT

I need to create method which returns my application object type as string :

TypeName(typeof( List<int>)) should return "List<int>" or
"System.Collections.Generic.List<int>"

TypeName(typeof( MyType<Customer>)) should return
"MyNamesp.MyType<MyBusiness.Customer>"

etc.


I tried

static string TypeName(Type type) {
return type.Name;
}

but this returns wrong names (? etc) for generic types.

How to get correct type name for generic types ?

Andrus.


CSharp/C# >> Return type name as string

by not_a_commie » Fri, 06 Jun 2008 02:57:11 GMT


You will need to use Type.GetGenericArguments and build up your own
string.

CSharp/C# >> Return type name as string

by Andrus » Fri, 06 Jun 2008 03:29:18 GMT

> You will need to use Type.GetGenericArguments and build up your own

Thank you.
I created method below. For initial tests it seems to work OK.
Is this best solution ?

Andrus.

/// <returns>type name as string</returns>
static string TypeName(Type type)
{

if (!type.IsGenericType)
return type.Name;

StringBuilder sb = new StringBuilder(type.Name);
sb.Append('<');
bool first = false;
foreach (Type t in type.GetGenericArguments())
{
if (first)
{
sb.Append(',');
first = false;
}
sb.Append(TypeName(t));
}
sb.Append('>');
return sb.ToString();
}

CSharp/C# >> Return type name as string

by not_a_commie » Fri, 06 Jun 2008 22:23:04 GMT

I think you mean 'if (!first)' and then you want to set it to true
inside that 'if' statement.

CSharp/C# >> Return type name as string

by Andrus » Mon, 09 Jun 2008 05:59:26 GMT

>I think you mean 'if (!first)' and then you want to set it to true

for type

DateTime?

this function returns invalid type name:

Nullable'1<DateTime>

How to force it to return correct nae:

DateTime?

Andrus.

CSharp/C# >> Return type name as string

by Marc Gravell » Mon, 09 Jun 2008 16:50:54 GMT

Well, strictly speaking, Nullable<DateTime> is the correct name,
give-or-take some namespaces. DateTime? is only C# specific. But you
could do this by checking for Nullable<T> as a special case. There is a
helper method as it happens; Nullable.GetUnderlyingType(Type):

Type nullableType = Nullable.GetUnderlyingType(type);
if (nullableType != null) return nullableType.Name + "?";

Marc

CSharp/C# >> Return type name as string

by Andrus » Tue, 10 Jun 2008 00:05:03 GMT

Marc,


It returns incorrect name:

Nullable`1<DateTime>


Thank you. I created method below. Initially

TypeName( typeof(System.Collections.Generic.List<string>) )

returns invalid type name which causes compile error :

System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b77a5c561934e089]]<System.String>

To force it to return

System.Collections.Generic.List<System.String>

I looked all type properties using debugger but havent found any property
which returns legal type name System.Collections.Generic.List .

So I take leftmost characters from FullName up to ` character .
Is this best solution ?

Andrus.



/// <summary>
/// Get full type name with full namespace names
/// </summary>
/// <param name="type">Type. May be generic or nullable</param>
/// <returns>Full type name, fully qualified namespaces</returns>
public static string TypeName(Type type)
{
Type nullableType = Nullable.GetUnderlyingType(type);
if (nullableType != null)
return nullableType.FullName + "?";

if (!type.IsGenericType)
return type.FullName;

StringBuilder sb = new StringBuilder(
type.FullName.Substring(0, type.FullName.IndexOf('`'))
);
sb.Append('<');
bool first = true;
foreach (Type t in type.GetGenericArguments())
{
if (!first)
{
sb.Append(',');
first = false;
}
sb.Append(TypeName(t));
}
sb.Append('>');
return sb.ToString();
}

Similar Threads

1. Covariant return type (was Variant return type)

2. Deducing return type from function name in compile time

3. The string returned by typeid(X).name()

4. Customize DataContractSerializer to use class name as tag name instead of base class name + type attribute

Hi,

in my data contract I have a member like this:

[DataMember]
public List<BaseClass> Items { get { ... } }

The property is serialized as a list of <BaseClass> tags with an
i:type attribute. It would be better for me to have <DerivedClass>
tags for the different subclasses. Is there a way to enforce that?

Achim

5. Method return type of a methond that returns different object types - Microsoft .NET Framework

6. Name of the .NET type is within a string

Hi,

I have a .NET type within a string like "System.Int16" or "System.DateTime".

How can I parse and and check if a string contains a valid value from that 
type?

I am trying to build a function like this:

IsValidType("123","System.Int16"); // Should return true
IsValidType("1a3","System.Int16"); // Should return false
IsValidType("6/21/2001","System.DateTime"); // Should return true
IsValidType("34/21/2001","System.DateTime"); // Should return false

Is there any wat to create a function like that without using a big 
switch(), case element?

Thank you,
Alan


7. Qualified type names and GetType(String) - CSharp/C#

8. error: 'string' does not name a type

What would cause this error?

Here is the code:

#include <string>
class name
{
	public:
		// default constructor
		void NAME()
		{
			FirstName = "John";
			MiddleName = "H.";
			LastName = "Doe";
		}

		// non-default constructor
		string NAME(string FN, string MN, string LN)
		{
			FirstName=FN;
			MiddleName=MN;
			LastName=LN;
		}

		// returns First Name, Middle Name, and Last Name in order
		void getFirstLast()
		{

		}

		// prints the first, middle, and last name
		void print()
		{

		}

	private:
		string FN, MN, LN;

}