This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
I'm new to c sharp. I"ve got an ASP.NET MVC Core 2.0 project and I need to populate a list inside a model and return that model to the page. My model looks like this:
public class PageModel
public string Title {get; set;}
public List<ChartGroups> Chart { get; set; }
}
public class ChartGroups
{
public string Freq { get; set; }
public string Head { get; set; }
}
To populate this I've got the following:
public PageModel GetChart(){
PageModel R = new PageModel();
R.Title = "Some Title";
R.Chart.Add(New ChartGroups {Freq ="Test", Head="Test2"});
R.Chart.Add(New ChartGroups {Freq ="Test3", Head="Test4"});
return(R);
}
The problem is I get an error saying I need to obstinate the object when I get to the R.Chart.Add... line. I've been doing this with drop down list and it works just fine....I'm sure I'm missing something simple just can't see it.
UPDATE:
I know that I need to obstinate the object, just not sure how to do so under this context.
You need to create an instance of the List<ChartGroups>() before you can start adding items to it. You can either do this in your GetChart() method:
public PageModel GetChart()
{
PageModel R = new PageModel();
R.Title = "Some Title";
R.Chart = new List<ChartGroups>(); //< ---
R.Chart.Add(New ChartGroups { Freq = "Test", Head = "Test2"});
R.Chart.Add(New ChartGroups { Freq = "Test3", Head = "Test4"});
return R;
}
Or in your PageModel class:
public class PageModel
{
public string Title { get; set; }
public List<ChartGroups> Chart { get; set; } = new List<ChartGroups>();
}
You need to Initialize the List. So for example, in your PageModel constructor you can do:
public class PageModel
{
public PageModel()
{
Chart = new List<ChartGroups>();
}
public string Title {get; set;}
public List<ChartGroups> Chart { get; set; }
}
Just to inform, you don't probably need the { set; } part of the Chart property since you are now initializing the property in the constructor, so you can just put it as
public List<ChartGroups> Chart { get; }
And then, if you wish, you can also you syntax like
public List<ChartGroups> Chart { get; } = new List<ChartGroups>();
Which would allow you to move the initialization out of the constructor.
Your list is null. So set it to an instance:
public List<ChartGroups> Chart { get; set; } = new List<ChartGroups>()
Related
I have 2 base classes which 1 for search criteria and other 1 for search results.
I also have 2 derived classes for User object versions of both of those.
When I put a breakpoint in the controller action I can see all properties are populated as I've hardcoded.
When I call this action directly in the browser, each of my derived object properties is null.
I'm guessing the JSON serialization is not able to tell the difference from the base class to the derived one.
Is there a way to solve this?
public class BaseSearchCriteria
{
public int Page { get; set; }
public int RecordsPerPage { get; set; }
}
public class BaseSearchResults
{
public int TotalResults { get; set; }
public virtual BaseSearchCriteria SearchCriteria { get; set; }
}
public class UserSearchCriteria : BaseSearchCriteria
{
public string Username { get; set; }
}
public class UserSearchResults : BaseSearchResults
{
public new UserSearchCriteria SearchCriteria { get; set; }
}
public JsonResult Search(UserSearchCriteria model)
{
var viewModel = new UserSearchResults
{
SearchCriteria = new UserSearchCriteria
{
Page = 1,
RecordsPerPage = 15
}
};
viewModel.TotalResults = 100;
return Json(viewModel, JsonRequestBehavior.AllowGet);
}
Maybe good way to deal with it is to use generics as Daniel A. White propose.
Sample gist here.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I´m attempting to fill a POCO object but I get the NullReferenceException - Object reference not set to an instance of an object, at line "objectAreas.position.Add(objectPositions);" I think I'm not initializing well but I don't see my mistake, let's see the code:
POCO OBJECT
public class GenericQuery
{
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
}
public sealed class Positions
{
public int idposition { get; set; }
public string positionname { get; set; }
}
public sealed class QueryAreasPositions
{
public int code { get; set; }
public string response { get; set; }
public List<Areas> areas { get; set; }
}
}
Filling It
GenericQuery.QueryAreasPositions objectAreasPositions = new GenericQuery.QueryAreasPositions();
var query = areaRepository.Get(); //Eager Loading EntityFramework List Object, see the AreaRepository at the end
objectAreasPositions.code = 123;
objectAreasPositions.response = "anything";
foreach (var area in query)
{
GenericQuery.Areas objectAreas = new GenericQuery.Areas();
objectAreas.idarea = area.IdArea;
objectAreas.areaname = area.Name;
foreach (var position in area.Position)
{
GenericQuery.Positions objectPositions = new GenericQuery.Positions();
objectPositions.idposition = position.IdPosition;
objectPositions.positionname = position.Name;
***objectAreas.position.Add(objectPositions);***//HERE
}
objectAreasPositions.areas.Add(objectAreas); //And maybe here
}
AreaRepository
public List<Area> Get()
{
using (var context = new Entities())
{
return context.Area.Include("Position").ToList();
}
}
I would appreciate any help/guide you can give me, Thanks.
You are never initializing objectAreas.position, hence the default value for a List<T> is null.
Since you are trying to call the Add method on a null reference, you are getting a NullReferenceException.
To fix this, you should initialize the property before using it:
objectAreas.position = new List<GenericQuery.Positions>();
Alternatively, you can add this logic on GenericQuery.Areas constructor, which would be more appropriate:
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
public class Areas()
{
positions = new List<Positions>();
}
}
Shouldn't you rather be doing like below. Your position is null cause not yet initialized and thus the said exception.
objectAreas.position = new List<Position>();
objectAreas.position.Add(objectPositions);
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have the following C# classes:
public class Locales
{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }
}
public class Region
{
public Center center { get; set; }
public East east { get; set; }
}
public class Center
{
public string title { get; set; }
}
public class East
{
public string title { get; set; }
}
public class Buttons
{
public string save { get; set; }
}
public class Fields
{
public Labels labels { get; set; }
}
public class Labels
{
public string firstName { get; set; }
public string lastName { get; set; }
public string chooseLocale { get; set; }
}
To sum up, Locales has Region, Buttons and Fields. Region has Center and East. Center and East have property title. Fields has Labels which has properties firstName, lastName and chooseLocale.
In a method (called GetLocale) I have the following code:
Locale englishLang = new Locale();
englishLang.region.center.title = "Center Region";
englishLang.region.east.title = "East Region - Form";
englishLang.buttons.save = "Save";
englishLang.fields.labels.firstName = "First Name";
englishLang.fields.labels.lastName = "Last Name";
englishLang.fields.labels.chooseLocale = "Choose Your Locale";
When I run the code, a "NullReferenceException was unhandled by user code" is thrown at the line : englishLang.region.center.title = "Center Region";
Am I doing something wrong in the way I have set the properties title, save, firstName, lastName and chooseLocale?
I tried adding the following block of code after Locale englishLang = new Locale(); and before englishLang.region.center.title = "Center Region"; but I still get the error message.
Region region = new Region();
Center center = new Center();
East east = new East();
Buttons buttons = new Buttons();
Fields fields = new Fields();
Labels labels = new Labels();
What am I doing wrong?
Your Locales object never instantiates its properties, nor does the consuming code instantiate them. As reference types, the properties in that class have a default value of null. So when you do this:
Locale englishLang = new Locale();
The following values are null:
englishLang.region
englishLang.buttons
englishLang.fields
Thus, you'll receive a NullReferenceException if you try to de-reference those fields, like you do here:
englishLang.region.center.title = "Center Region";
That line of code attempts to de-reference englishLang.region by referring to its center property. But region is null because it hasn't been instantiated yet.
The best place to instantiate those in the case of these DTO classes would probably be in their constructors. Something like this:
public class Locales
{
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }
public Locales()
{
region = new Region();
buttons = new Buttons();
fields = new Fields();
}
}
That way consuming code doesn't have to do this manually each time, the fields are automatically instantiated by the constructor any time you create an instance of Locales. Naturally, you'll want to repeat this same pattern for your other objects.
You have to instantiate each and every object:
Locale englishLang = new Locale();
englishLang.region = new Region();
englishLang.region.center = new Center();
englishLang.region.center.title = "Center Region";
and so on...
Or you can instantiate the dependent objects in the constructor of the parent class.
You have to initialize the properties/sub properties before assigning values:
Locale englishLang = new Locale();
englishLang.region = new Region();
englishLang.region.center = new Center();
englishLang.region.center.title = "Center Region";
You're using automatic properties, and by default they return null for reference types. You need to initialize the properties, probably in the constructor:
public class Locales
{
public Locales()
{
this.region = new Region();
this.buttons = new Buttons();
this.fields = new Fields();
}
public Region region { get; set; }
public Buttons buttons { get; set; }
public Fields fields { get; set; }
}
You'll also need to add similar code to the other classes.
I have a couple of classes I'm having difficulty populating:
public class ta_Room
{
public string url { get; set; }
public double price { get; set; }
public string room_code { get; set; }
}
public class ta_Hotel2
{
public int hotel_id { get; set; }
public Dictionary<string, ta_Room> room_types { get; set; }
}
In my controller I have:
[HttpGet]
public ta_Hotel2 hotel_inventory() //int api_version, string lang)
{
{
ta_Room room = new ta_Room();
room.price = 23;
room.room_code = "1";
room.url = "http://www.nme.com";
ta_Hotel2 hotel = new ta_Hotel2();
hotel.room_types.Add("Single", room);
However I get a NullReferenceException on the last line above.
In the screenshot below, it shows both the hotel and room object have been created - can anyone please advise what I've done wrong please?
Thank you,
Mark
The error is due to the fact you are not building the instance of room_types inside ta_Hotel2. You should add a constructor as follows or just instantiate it within hotel_inventory():
public class ta_Hotel2
{
public int hotel_id { get; set; }
public Dictionary<string, ta_Room> room_types { get; set; }
public ta_Hotel2()
{
room_types = new Dictionary<string, ta_Room>();
}
}
Also note that, from an encapsulation point of view, I would also make the setter of room_types private after that. And, as a side note, I would also rename your classes and members as suggested here.
You cannot assign a value to hotel.room_types before you initialize. Like the way Efran suggest, use a public constructor in ta_Hotel2 class will solve your issue.
For Windows 8 application development environment.
Code:
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
listView.ItemsSource = deserialized; // error
Data model:
public class C
{
public List<Y> programs { get; set; }
public string name { get; set; }
public int code { get; set; }
}
public class RootObject
{
public List<C> cs { get; set; }
public string date { get; set; }
}
public class Y
{
public string category { get; set; }
public string time { get; set; }
public string name { get; set; }
}
What can I do ? I don't find solution.
ItemsSource is looking for an IEnumerable, but you're providing a single object in RootObject. You'd get the same error if you create one of your RootObject instances in code and try the same assignment.
What specifically should be displaying in the list? If you simply change your code to:
listView.ItemsSource = deserialized.cs;
the listView should display your C objects.
I always have trouble figuring out how to go from the serializer output. I do have working code (windows 8 store) that I'm pasting below. It is pretty obvious what it does.
HttpResponseMessage responseGetEmailByPersonsBare =
await clientGetEmailByPersonsBare.PostAsync(UrlBase + EmailDetailGetEmailByPersonsBare, contentGetEmailByPersonsBare);
Stream myStream = await responseGetEmailByPersonsBare.Content.ReadAsStreamAsync();
var djsGetEmailByPersonsBare = new DataContractJsonSerializer(typeof(AEWebDataStructures.RootObjectEmailDetail));
var rootObjectEmailDetail = (AEWebDataStructures.RootObjectEmailDetail)djsGetEmailByPersonsBare.ReadObject(myStream);
responseGetEmailByPersonsBare.EnsureSuccessStatusCode();
returnTaskInfo.EmailDetails = rootObjectEmailDetail.Data;
returnTaskInfo.StatusReturn = AEWebDataStructures.StatusReturn.Success;