开发者

Object is null. How to set it? c#

开发者 https://www.devze.com 2023-01-13 22:31 出处:网络
I have a variable FirstThreads of type List<Thread>. I am trying to do the following, but FirstThreads is always null.

I have a variable FirstThreads of type List<Thread>.

I am trying to do the following, but FirstThreads is always null.

FirstThreads.AddRange(Threads.Skip<Thread>(PageIndex * PageSize)
            .Take<Thread>(PageSize));

I can't do this:

FirstThreads = FirstThreads.AddRange(Threads.Skip<Thread>(PageIndex * PageSize)
                                            .Take<T开发者_如何学编程hread>(PageSize));

Do you have any idea how to solve this?


Before you can interact with the FirstThreads variable, you need to make the variable refer to a List<Thread> instance, like this:

firstThreads = new List<Thread>();

You can also write

firstThreads = Threads.Skip<Thread>(PageIndex * PageSize).Take<Thread>(PageSize)


You need to initialize your List<FirstThreads> first.

The default value of any object is null.

For example:

List<FirstThreads> firstThreads = new List<FirstThreads>();
firstThreads.AddRange(collection);


you need to instantiate the list first, I assume it is a List<Thread>?

so

FirstThreads = new List<Thread>();


You need to instantiate the List object:

List<Thread> FirstThreads = new List<Thread>();


When in doubt the 'new' keyword is always worth a shot


THe thing is, if you write FirstThreads.AddRange you're implying FirstThreads is an object with the AddRange method; but FirstThreads is null, that means that it's empty (so it has no methods).
You would have to make FirstThreads an empty list:

FirstThreads = new List<Thread>();


FirstThreads either was set to null or is never initialized. Either way my guess is you need to create an object to assign to it.

FirstThreads = new <-- visual studio will auto complete object creation code


You can use

FirstThread = 
    new List<Thread>(Threads.Skip<Thread>(PageIndex * PageSize)
                            .Take<Thread>(PageSize));

Or if you're not sure whether it has items and is already instantiated

(FirstThread ?? FirstThread = new List<Thread>())
    .AddRange(Threads.Skip<Thread>(PageIndex * PageSize)
    .Take<Thread>(PageSize));

Note:

You can probably take out the <Thread> for the Skip and Take methods, as it will be inferred.

0

精彩评论

暂无评论...
验证码 换一张
取 消