Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

determine complex type from a primitive type using reflection

I am writing a tool where I need to reflect upon methods and if the parameters of the methods are complex type, then I need to certain type of actions such as instantiating them etc.

Now I saw the IsPrimitive property in the Type variable. However, it shows string and decimal as complex types, which technically isn't incorrect. However what I really want is to be able to distinguish developer created class types from system defined data types.

Is there any way that I can do this?

like image 592
Nilotpal Das Avatar asked May 12 '10 04:05

Nilotpal Das


3 Answers

decimal certainly is a "complex type"; C# may have a keyword for it, but it is not a CLI primitive. String you could argue either way - it is actually a type all to itself (indeterminate size, etc - the only things remotely comparable are arrays).

However; there is simply no way to determine what you are wanting here. The best you can do is to check for known system assembles (or maybe signing keys). After all, I can write an assembly called System.something.dll or Microsoft.something.dll, with types in the System.Foo.Bar namespace (this also depends on how paranoid you want to be, of course).

It may be easier to get devs to explicitly mark their own types that you want to treat in a speicial way - either via an attribute or an interface.

like image 166
Marc Gravell Avatar answered Nov 14 '22 01:11

Marc Gravell


Came across this thread while I was doing a search. I was looking for a solution for this myself and found out that you can also check the namespaces to see if the property has been defined in your own namespace.

if (property.PropertyType.Namespace.StartsWith("MyApp.MyNamespace"))
{ 
      // logic for properties in MyNamespace
}

Hope this helps someone.

like image 20
Davy Avatar answered Nov 14 '22 01:11

Davy


I 'm not sure if there is a more elegant method, but I imagine that if you check the type's Namespace or AssemblyQualifiedName against namespace System and/or the system assemblies it will work out fine.

like image 2
Jon Avatar answered Nov 14 '22 01:11

Jon