Set value to a sub class from main class [duplicate]
Set value to a sub class from main class [duplicate]
This question already has an answer here:
I am trying to set value to StorageFile
who lives inside MainFolderDisplay
as a list. But the problem is i am getting exception like bellow. Whats wrong i am doing here?
StorageFile
MainFolderDisplay
System.NullReferenceException: 'Object reference not set to an
instance of an object.'
Controller:
var mainFolder = new MainFolderDisplay();
mainFolder.StorageFile.Add(new StorageFile
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
);
Model:
using Test.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Test.ViewModels
public class MainFolderDisplay
public int MainFolderId get; set;
public string MainFolderName get; set;
public int UserId get; set;
public List<SubFolder> SubFolders get; set;
public List<StorageFile> StorageFile get; set;
public class SubFolderDisplay
public int SubFolderId get; set;
public string SubFolderName get; set;
public int MainFolderId get; set;
public List<StorageFile> StorageFile get; set;
public class StorageFileDisplay
public int FileId get; set;
public string AwsUniqueFileName get; set;
public string UserDisplayFileName get; set;
public int UserId get; set;
public int FolderType get; set;
public int RelatedFolderId get; set;
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
2 Answers
2
Your "StorgaeFile" property is not initialized before using :
var mainFolder = new MainFolderDisplay();
mainFolder.StorageFile = new List<StorageFile>
new StorageFile
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
;
The better way is to change the "MainFolderDisplay" class implementation to handle initialization :
public class MainFolderDisplay
private List<StorageFile> _storageFile;
public int MainFolderId get; set;
public string MainFolderName get; set;
public int UserId get; set;
public List<StorageFile> StorageFile
get => _storageFile ?? (_storageFile = new List<StorageFile>());
set => _storageFile = value;
and now use it without worry :
mainFolder.StorageFile.Add(
new StorageFile
AwsUniqueFileName = "asasas",
FileId = 0,
FolderType = 0,
RelatedFolderId = 0,
UserDisplayFileName = "",
UserId = 0,
);
The StorageFile list isn't initialised.
mainFolder.StorageFile = new List<StorageFile>();
I would suggest renaming this property to StorageFiles to imply it's a collection.
mainFolder.StorageFiles = new List<StorageFile>();