HowTo create an object if you only have its type as string

Sometimes you have only the type of an object, which you want to create. Meaning you want to create an object dynamically. This is how you would achieve your goal:

In my case I wanted to create a SPField from its typename.

 1: string typename = “Microsoft.SharePoint.SPFieldText, Microsoft.SharePoint, “+

<span class=lnum>   2:  </span>    <span class=str>"Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"</span>;
 3: Type t = Type.GetType(typename, true, true);
<span class=lnum>   4:  </span><span class=kwrd>object</span> newObject = System.Activator.CreateInstance(t, 
 5:  BindingFlags.SetProperty, new object[] { fields, "Title" });

I know one constructor for a SPField is to create a new object with the SPFieldCollection and its name.

The problem was that the constructor could be found.

You can view all available constructors with:

 1: ConstructorInfo[] constructors = t.BaseType.GetConstructors();

After looking back into the SDK, I noticed that SharePoint can be so easy. You can create a SPField like this:

 1: SPField newField = new SPField(fields, “SPFieldText”, “new Field Name”);

Next time I will remember 🙂

Keywords: Create SPField from typename, Erstellen eines spfield von seinem typ namen