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

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

Related

C# linq DefaultIfEmpty() NullReferenceException Value cannot be empty. Parameter name: Source [duplicate]

This question already has answers here:
Value cannot be null. Parameter name: source
(20 answers)
Closed 2 years ago.
I have a problem
How can I inquire in a linq correctly
Get a mistake NullReferenceException every time
public class Model
{
public int Nmb { get; set; }
public string _UserId { get; set; }
}
public static List<Model> _models_List { get; set; }
string user = "test name";
int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).DefaultIfEmpty(0).First();
if (test == 0)
{
Model obj = new Model();
obj._UserId = user;
obj.Nmb = 1;
_models_List.Add(obj);
}
I tried to correct the code like this
But I get the same mistake
NullReferenceException
Value cannot be empty. Parameter name: Source
int test = _models_List.Where(o => o._UserId == user).Select(o => o.Nmb).FirstOrDefault();
Please Help
The list _models_List is empty, to solve the issue replace the following code:
public static List<Model> _models_List { get; set; }
with:
public static List<Model> _models_List { get; set; } = new List<Model>();

Use Class as interface in List<IClass> [duplicate]

This question already has answers here:
C# List<Interface>: why you cannot do `List<IFoo> foo = new List<Bar>();`
(9 answers)
Closed 4 years ago.
I'm having issues trying to use a list of interfaces. (I'm probably terrible at explaining this, I've only been coding for a year now, but here goes.)
I have an interface:
public interface IComboBoxItem
{
string Display { get; set; }
int? IntValue { get; set; }
string StringValue { get; set; }
}
And a class that implements that interface:
public class GenericComboBoxItem : IComboBoxItem
{
public virtual string Display { get; set; }
public virtual int? IntValue { get; set; }
public virtual string StringValue { get; set; }
public GenericComboBoxItem(string stringValue)
{
Display = stringValue;
StringValue = stringValue;
IntValue = null;
}
}
Then I take a list of these in my View Model's constructor:
public class TransactionModalVM
{
public TransactionModalVM(List<IComboBoxItem> categoryList)
{
CategoryList = categoryList;
}
public List<IComboBoxItem> CategoryList { get; set; }
}
Yet when I attempt to pass them in
public class TransactionsOM
{
internal TransactionModalVM GetTransactionModalVM()
{
return new TransactionModalVM(new List<GenericComboBoxItem>() { new GenericComboBoxItem("Not yet Implemented") });
}
}
I get an error that it can't convert from List<GenericComboBoxItem> to List<IComboBoxItem>.
I originally ran into this when I was using a class that inherited from GenericComboBoxItem and thought I just had to use and interface instead of inheritance but then found that both classes failed and figured there but be some trick I'm missing here.
This may possibly be a duplicate of something, but I've spent the morning searching with no luck and thought I'd post a new question.
Much appreciation in advance for any help!
It would be a good idea to research covariance and contravariance in C#.
However in your particular case,using an IReadOnlyList instead of a list in your view model would solve your problem.
public class TransactionModalVM
{
public TransactionModalVM(IReadOnlyList<IComboBoxItem> categoryList)
{
CategoryList = categoryList;
}
public IReadOnlyList<IComboBoxItem> CategoryList { get; set; }
}
A List<GenericComboBoxItem> is convertible to an IReadOnlyList<IComboBoxItem>, but not to a List<IComboBoxItem>

C# dynamically set property When Property is a class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
Hi i have a Number of Properties and My properties like
public XYZ()
{
xyz = new xyz1();
xyz2 = new xyz2();
}
public xyz1 xyz1 { get; set; }
public xyz2 xyz2 { get; set; }
}
public class xyz1
{
public string fName { get; set; }
public string lnameget; set;}
}
public class xyz2
{
public string city { get; set; }
public string state
}
While i am setting my property on runtime i am getting exception object reference set to null.
XYZ model = new XYZ();
PropertyInfo propertyInfo = model.GetType().GetProperty("fName");
propertyInfo.SetValue(model, Convert.ChangeType(item.InnerText, propertyInfo.PropertyType), null);
Please help me
model has no fName property, but model.xyz1 does.

Filling POCO Object with List inside a List [duplicate]

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

'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.

Categories

Resources