Filling POCO Object with List inside a List [duplicate] - c#

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);

Related

Populate a List <> not a Select List [duplicate]

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>()

why null reference exception in List<decimal> [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
i have a problem, i created an object in C# like this:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
}
then i do something like this:
logisva logi = new logis();
logi.codigo = oDataReader.GetValue(0).ToString();
logi.Necesidades.Add(0);
But when i execute my code i get a null reference exception error. Object reference not set to an instance of an object. on the last line logi.Necesidades.Add(0);
Any idea why i get this error?
In C# the properties do not initialize/create the List<ofType> object automatically. You need to create the list explicitely:
public class logis
{
public string codigo { get; set; }
public List<decimal> Necesidades { get; set; }
decimal SumaNecesidades{get;set;}
public logis()
{
this.Necesidades = new List<decimal>();
}
}
Another option is to create the list in the getter resp. setter (so to say your own lazy initialization, downside - introduces more code, advantage no need to override every contructor):
public class logis
{
public string codigo { get; set; }
decimal SumaNecesidades{get;set;}
private List<decimal> necesidades = null;
private void initNecesidades()
{
if (this.necesidades == null)
{
this.necesidades = new List<decimal>();
}
}
public List<decimal> Necesidades
{
get
{
this.initNecesidades();
return this.necesidades;
}
set
{
this.initNecesidades();
this.necesidades = value;
}
}
}
Yet another option would be to use the new C# 6.0 features (if it is an option to use/already using the latest .NET Framework version) as already suggested in the comments by #Jcl:
public List<decimal> Necesidades { get; set; } = new List<decimal>()

'System.NullReferenceException' [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I am writing a LINQ query. But, i am getting null object reference error for Model.StudentSummary.StudentDetails.
I put breakpoint on following foreach and when i mouse over Model.StudentSummary.StudentDetails i see StudentDetails is null.
I have initialized the whole model class than why it didn't initialize List<StudentDetails> in StudentSummary class?
foreach (Summary summary in Model.summaryData)
{
Model.StudentSummary.StudentDetails.Add(new SafetyDetails
{
Name = summary.Name,
ManTimeWorked = summary.TotalTime,
});
}
Model.cs
public class Report : BaseReportModel
{
public Report()
{
StudentSummary = new StudentSummary();
}
public StudentSummary StudentSummary { get; set; }
}
public class StudentSummary
{
public string Name { get; set; }
public List<StudentDetails> StudentDetails { get; set; }
}
Just because you initialized the object doesn't mean that all of its properties are initialized: each of those carries its default value until you change it, and the default for a List (or any class-type object) is null (more details in this post). You need to initialize the list.
You can inline this in your Report constructor like:
public class Report : BaseReportModel
{
public Report()
{
StudentSummary = new StudentSummary
{
StudentDetails = new List<StudentDetails>()
}
}
public StudentSummary StudentSummary { get; set; }
}
Another option is to initialize it in StudentSummary's constructor itself, which keeps the class in a nice state from the beginning without any additional work:
public class StudentSummary
{
public StudentSummary()
{
StudentDetails = new List<StudentDetails>();
}
public string Name { get; set; }
public List<StudentDetails> StudentDetails { get; set; }
}
This has a tradeoff: if you already have a List<StudentDetails> that you want to initialize it to, you needlessly create a new list - but if your regular use case is adding them as you do in the example code, it shouldn't be an issue.
If you're expecting StudentSummary.StudentDetails to be instantiated at the same time as StudentSummary you need to manually do it in the StudentSummary constructor, as you do with the StudentSummary in the Report constructor.

WCF: Object Reference Not Set To Instance Of a an Object [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a CibilResponse Class that has properties that are of class type (TUEF class). I am trying to assign value to CibilEnquiryEnq.Tuef.Version but i am getting null reference error. Before you mark this question as duplicate let me mention that I have read some of the similar questions and their answers on SO and post which I have initialized tuef in the constructor as you can see in my code. Can you please point out if you can what is it that I am doing wrong?
ICIBIL.cs
[ServiceContract]
public interface ICIBIL
{
[OperationContract]
string InsertCibil(CibilResponse cibilResponse);
[OperationContract]
string GenerateEnquiry(CibilEnquiry testObj);
}
[DataContract]
public class CibilResponse
{
[DataMember]
public string ResponseString { get; set; }
[DataMember]
public string Business { get; set; }
[DataMember]
public string MkrId { get; set; }
}
[DataContract]
public class CibilEnquiry
{
[DataMember]
public TUEF Tuef { get; set; }
public CibilEnquiry()
{
this.Tuef = new TUEF();
}
}
[DataContract]
public class TUEF
{
[DataMember]
public string SegmentTag { get; set; }
[DataMember]
public string Version { get; set; }
[DataMember]
public string MemberReferenceNumber { get; set; }
}
Appication :
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilEnquiryEnq.Tuef.Version = "123";// null reference error here
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
Can you try the below. C# is case sensitive.
using CbilFileReader.CibilWcfService;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CIBIL obj = new CIBIL();
CibilEnquiry CibilEnquiryEnq = new CibilEnquiry();
TUEF objtuef = new TUEF();
objtuef.Version = "123";
CibilEnquiryEnq.Tuef = objtuef;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
}
}
}
This might do the trick for you
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilWcfService.CibilEnquiry.Tuef ObjTUEF = new CibilWcfService.CibilEnquiry.Tuef();
ObjTUEF.Version="123";
CibilEnquiryEnq.Tuef = ObjTUEF;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);

Exception when adding item to list<t>

I always get a "An unhandled exception of type 'System.NullReferenceException' occurred in myapp.exe" when code reaches _match.Players2.Add(_hero);
I am not sure why, I initialized _match as well as _hero, when I debug I see that there are no null values. I am not sure why I am getting this exception, am I missing something?
Here is my code:
public static List<MyDotaClass.MatchHistory> GetMatchHistory(string uri)
{
var HeroCollection = new List<MyDotaClass.DotaHero>();
var MatchCollection = new List<MyDotaClass.MatchHistory>();
string response = GetDotaWebResponse(uri);
dotadata.Dota.MatchHistoryRootObject matches = JsonConvert.DeserializeObject<dotadata.Dota.MatchHistoryRootObject>(response);
foreach (var match in matches.result.matches)
{
var _match = new MyDotaClass.MatchHistory();
_match.MatchID = match.match_id.ToString();
foreach (var player in match.players)
{
var _hero = new MyDotaClass.DotaHero();
foreach(var h in heros)
{
if(player.hero_id.ToString().Equals(h.HeroID))
{
_hero.HeroName = h.HeroName;
_hero.HeroNonCleanName = h.HeroNonCleanName;
_hero.HeroID = h.HeroID;
_match.Players2.Add(_hero);
}
}
}
MatchCollection.Add(_match);
}
return MatchCollection;
}
public class MyDotaClass
{
public class DotaHero
{
public string HeroName { get; set; }
public string HeroNonCleanName { get; set; }
public string HeroID { get; set; }
}
public class MatchHistory
{
public string MatchID { get; set; }
//public List<DotaHero> Players { get; set; }
public List<MyDotaClass.DotaHero> Players2 { get; set; }
}
UPDATE:
For those interested in Dota, I lost all of my original code so I am rewriting and doing my best to make a tutorial out of it. http://uglyvpn.com/2014/07/21/dota-2-net-c-tool-pt1/
Make sure the list in Players2 is initialized properly. It could be done in your foreach loop, like this:
foreach (var match in matches.result.matches)
{
var _match = new MyDotaClass.MatchHistory();
_match.MatchID = match.match_id.ToString();
_match.Players2 = new List<MyDotaClass.DotaHero>();
...
But that's not a great design. It would be more robust to initialize it in the MatchHistory constructor, like this:
public class MatchHistory
{
public string MatchID { get; set; }
//public List<DotaHero> Players { get; set; }
public List<MyDotaClass.DotaHero> Players2 { get; private set; }
public MatchHistory() {
this.Players2 = new List<MyDotaClass.DotaHero>();
}
}
Note that I have also made the setter private here, as there should be no need to modify the value of this property after it's been initialized in the constructor.
It is look like your Players2 collection is not instantiated, so do it first:
this.Players2 = new List<MyDotaClass.DotaHero>();
and then you would be able to refer and use it:
_match.Players2.Add(_hero);
As for where to instantiate it, do it in the constructor of MatchHistory:
public MatchHistory() {
this.Players2 = new List<MyDotaClass.DotaHero>();
}
This is a good practice, because next time, even if you will forget to instantiate it, the constructor will do it automatically for you.
Otherwise, you'd keep getting: System.NullReferenceException
UPDATE:
You can't use this in a static context, change this method in order to enjoy from the constructor-base instantiating:
public static List<MyDotaClass.MatchHistory> GetMatchHistory(string uri)
to this:
public List<MyDotaClass.MatchHistory> GetMatchHistory(string uri)
You initialized the MatchHistory instance but not the Players2 property so it's still null.
You probably want to allocate it in the constructor like this although there are other options;
public MatchHistory()
{
Players2 = new List<MyDotaClass.DotaHero>();
}
PS LoL > Dota :p

Categories

Resources