Over 5 years of experience creating SharePoint CSOM code and I’m writing about something that basic.

Why? Guess just one too many times I’ve seen how people do it wrong. But I understand why. I’ll repeat what I’ve already said/wrote on multiple occasions. It’s all Microsoft’s fault. Microsoft failed to document and explain how to write good CSOM code. Well, they’ve even failed to explain what CSOM is.

Simple task: Set some user as a value of some field.

But before we can set the value, let’s see how to retrieve it.

var context = new ClientContext(webUrl);
var web = context.Web;
var list = web.Lists.GetListByTitle("Sample");
var item = list.GetItemById(1);

context.Load(item);
context.ExequteQuery();

var fieldValue = item["Author"];

So, what’s the type of fieldValue object? We know that “Author” field is single user. So let’s see what MSDN says on the topic.

Field Type CSOM Expando Field Value Type Meaning
User When its value is undefined it MUST be CSOM a null reference, otherwise it must be CSOM Object. A lookup to a particular user in the User Info list.

Well, that’s about as helpful as:

If the value is null then it’s null. If it’s not null, then it’s an object.

or:

42

Armed with answer to the Ultimate Question of Life, the Universe, and Everything, we check ourselves.

Field type CSOM value
Single user FieldUserValue
Multi user FieldUserValue[]

And we go to the wrong conclusion:

If I want to set value user field we need to use FieldUserValue class.

var currentUser = web.CurrentUser;
context.Load(currentUser, user => user.Id); //Let's do it less terrible
context.ExecuteQuery();

item["CurrentUser"] = new FieldUserValue { Id = currentUser.Id };
item.Update();
context.ExecuteQuery();

No you don’t!

item["CurrentUser"] = web.CurrentUser;
item.Update();
context.ExecuteQuery();

Result:

  • Removed 50% of code, making it more maintainable.
  • Removed 50% of CSOM calls, making it execute in about 50% of time and put less stress on SharePoint server and network.

These will work too:

item["OtherUser"] = web.EnsureUser(@"contoso\dstarkowski");
item["Group"] = web.AssociatedOwnersGroup;