I have a class:
public class TaskDiplayModel
{
public int taskId { get; set; }
[DisplayName("Task Description")]
public string description { get; set; }
[DisplayName("Priority")]
public string priority { get; set; }
[DisplayName("State")]
public string state { get; set; }
[DisplayName("Due By")]
public DateTime deadline { get; set; }
[DisplayName("Created By")]
public PersonObject created_by { get; set; }
[DisplayName("Assigned To")]
public PersonObject assigned_to { get; set; }
[DisplayName("Category")]
public string category { get; set; }
[DisplayName("Sub Category")]
public string subCategory { get; set; }
[DisplayName("Created")]
public DateTime createdDate { get; set; }
[DisplayName("Updated")]
public DateTime lastUpdatedDate { get; set; }
[DisplayName("Updated By")]
public PersonObject lastUpdatedBy { get; set; }
}
I then have another class which inherits from this class:
public class TaskModifyModel : TaskDiplayModel
{
public int priorityId { get; set; }
public int stateId { get; set; }
public int categoryId { get; set; }
public int subCategoryId { get; set; }
public SelectList states { get; private set; }
public SelectList priorities { get; private set; }
public SelectList categories { get; private set; }
public SelectList subCategories { get; private set; }
public TaskModifyModel()
{
SetupReferenceData(0);
}
public TaskModifyModel(int taskId)
{
var taskService = new TaskService();
var task = taskService.GetTask(taskId);
}
}
In my application, I create a TaskModifyModel object. However, string fields from the base class are null. I’d expect them to have been created and be String.Empty. But I get exception when I try to access them. Am I missing something?
These are MVC3 Models, by the way…. And code from the classes have been omitted as I think it’s irrelevant to the question.
in .NET, the default value for a string is
null, notString.Empty, so unless you specifically set the values of the properties toString.Empty, they will remainnull.Assuming you want your string properties to default to an empty string instead of null, you would normally do this either by setting them in the constructor:
Or by using a field-backed property instead of an auto property, and setting the backing field:
Personally I usually use the first option, doing it in the constructor, because it is less to code.