Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

After some poking around I came across this article. It made me realize that I need to change my method's signature from:

public T GetField<T>(ClientContext clientContext, string field title, FieldType type)

to

public T GetField<T>(ClientContext clientContext, string field title, FieldType type)
    where T : ClientObject

This makes the cast work. Hooray!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.