I am writing a method that is supposed to create a SharePoint list field. I want to be able to make my method return the newly created field. The problem that I am facing is that list.Fields.AddFieldAsXml(...) (that is the Client Object Model's method that calls the creation of field in SharePoint) returns an object of type Field. I want, however, to cast to particular field type and that casting doesn't work.
Here's the method:
public T GetField<T>(ClientContext clientContext, string field title, FieldType type)
{
Field field;
// The following method creates a specific field and returns the Field object
// but I want to cast it later on to get the more specific field class, e.g. 'FieldText'
field = CreateMyField(type, field);
// The following cast won't work because of the 'T'
return clientContext.CastTo<T>(field);
}
I am getting the compile error
The type
'T'cannot be used as type parameter'T'in the generic type or method'Microsoft.SharePoint.Client.ClientRuntimeContext.CastTo<T>(Microsoft.SharePoint.Client.ClientObject)'. There is no boxing conversion or type parameter conversion from'T'to'Microsoft.SharePoint.Client.ClientObject'
If I use a concrete class instead of the T, e.g. FieldText, the cast works like a charm.
My question is: Is there a way to make the cast work with generics? Thanks.