What is the proper way to declare a Microsoft class to use in my code.

William Thompson 120 Reputation points
2024-09-17T20:57:02.1+00:00

What is the proper way to declare a Microsoft class to use in my code. The quick and dirty way I am doing it here, I know, is not correct

Microsoft SharePoint.Client.List newList = null;

I think it is something like this

Microsoft.SharePoint.Client.List newList = new Microsoft.SharePoint.Client.List();

proper-way

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,927 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 54,316 Reputation points
    2024-09-17T21:22:55.13+00:00

    Your terminology is a little confusing. If you want to create an instance of a type/class that is defined by somebody else then it is something like this.

    Microsoft.SharePoint.Client.List newList = new Microsoft.SharePoint.Client.List();
    
    //Or the shorter version
    var newList = new Microsoft.SharePoint.Client.List();
    

    The warning you're getting is because you're trying to assign null to a variable that is not typed as supporting null. That means you're building newer (e.g. NET 6+) code and you have enabled nullable reference types (the default).

    0 comments No comments

  2. Jiachen Li-MSFT 31,326 Reputation points Microsoft Vendor
    2024-09-18T05:44:06.48+00:00

    Hi @William Thompson ,

    The List class in the Microsoft.SharePoint.Client namespace cannot be instantiated directly using the new keyword. Instead, you should use the ListCreationInformation class to create a new list.

    using Microsoft.SharePoint.Client;
    
    // Assuming you have a ClientContext object named clientContext
    ClientContext clientContext = new ClientContext("http://YourSharePointSiteUrl");
    
    ListCreationInformation creationInfo = new ListCreationInformation();
    creationInfo.Title = "New List Title";
    creationInfo.TemplateType = (int)ListTemplateType.GenericList;
    
    List newList = clientContext.Web.Lists.Add(creationInfo);
    clientContext.ExecuteQuery();
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.