0

I have a long list of Objects in C# that I would like to script a series of "unit test stubs" for via MvcScaffolding.

I would like to be able to load an object's metadata and loop through the object's public properties.

However, in the context I do not want to (and in some cases cannot) create actual copies of the objects them.

Is there a way in C# to read the public properties of an object if I only have the name of the type in a string?

I'm trying to load the properties in a T4 template

For example I am trying:

<#@ Template Language="C#" HostSpecific="True" Inherits="DynamicTransform" #>
<#@ assembly name="C:\www\myproject\Web\bin\MyCustomAssembly.dll" #>
<#@ Output Extension="cs" #>
<#@ import namespace="MyCustomAssembly" #>

[TestClass]
public class <#= Model.PluginName #>ServiceTest
{
    // Example model value from scaffolder script: <#= Model.ExampleValue #>
    // 
<# 
    Type foo = Type.GetType("MyCustomAssembly."+Model.PluginName + "Service");
    if (foo == null) {
#>
// <#= "NULL" #>
<# } else {  
        // Output one generic UnitTest per Property in the object type
   } #>

}

}

Alex C
  • 16,624
  • 18
  • 66
  • 98

2 Answers2

2

Like this:

foreach (PropertyInfo p in Type.GetType(typeName).GetProperties())
{
    Console.WriteLine(p.Name);
}
Itiel
  • 339
  • 2
  • 14
1

if you have the type's fully-qualified name then you can use Type.GetType(string) method.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184