This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I have a class with this:
public class myDataType
{
public class GetInvoice
{
public string InvoiceID { get; set; }
public string InvoiceNumber { get; set; }
public decimal InvoiceAmount { get; set; }
public List<InvoiceRow> Rows { get; set; }
}
public class InvoiceRow
{
public decimal RowQty { get; set; }
public string RowCode { get; set; }
public string RowDescription { get; set; }
}
}
And when I want to add data has th
using static test.myDataType;
...
private void LoadData()
{
GetInvoice Invoice = new GetInvoice();
Invoice.InvoiceID = "0a8625e5-62f6-4ad7-a8bf-ab04b1158392";
Invoice.InvoiceNumber = "Inv-001";
Invoice.InvoiceAmount = 100;
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100", RowDescription = "Item C100"});
}
When try to add the row:
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100",
RowDescription = "Item C100"});
Show me this error "System.NullReferenceException: 'Object reference not set to an instance of an object'"
I think i have a sintax o wrong way to do it
Can someone help?
Thanks in advance
It's not a syntax error, you just haven't initialised the list.
With
public List<InvoiceRow> Rows { get; private set; }
you've declared a place to hold the list, but haven't created the list itself.
(If an analogy helps, imagine you've drawn a line on the wall of your house where you're going to put up a bookshelf, but you haven't actually screwed the shelf to the wall yet - that's the situation your code is in).
If you want the list to always be available you can either initialise it automatically through the property declaration, or in the constructor of the class. Alternatively of course you could leave the calling code to initialise it.
This version just makes it part of the property declaration:
public List<InvoiceRow> Rows { get; private set; } = new List<InvoiceRow>();
You need first to initialize list Rows before you add element to it.
For example in GetInvoice class you can add:
public List<InvoiceRow> Rows { get; set; } = new List<InvoiceRow>();
List is reference type in C# so it needs to be initialized before being used.
If you want to do that in LoadData() method you can do in this way:
private void LoadData()
{
GetInvoice Invoice = new GetInvoice();
Invoice.InvoiceID = "0a8625e5-62f6-4ad7-a8bf-ab04b1158392";
Invoice.InvoiceNumber = "Inv-001";
Invoice.InvoiceAmount = 100;
Invoice.Rows = new List<InvoiceRow>();
Invoice.Rows.Add(new InvoiceRow { RowQty = 1, RowCode = "C100", RowDescription = "Item C100" });
}
Related
I have three classes:
public class M2ArticleMain
{
public int Id { get; set; }
public List<M2ArticleAttributeWeb> Attribut_Web { get; set; }
}
public class M2ArticleAttributeWeb
{
public int Web_Id { get; set; }
public M2ArticleTmpMainSkus Variants { get; set; }
}
public class M2ArticleTmpMainSkus
{
public DateTime TimeAdded { get; set; }
public List<string> Skus { get; set; }
}
And I have two Lists in my code like this:
List<M2ArticleMain> data = new List<M2ArticleMain>();
List<M2ArticleAttributeWeb> attb = new List<M2ArticleAttributeWeb>();
In some part of my code firstly I (from foreach loop) add data to attb list where I add only only some data (because I don't have all data at this point), like this:
...
attb.Add(new M2ArticleAttributeWeb
{
Web_id = item.Id, //(item is from foreach loop)
Variants = null //this is **importat**, I left null for later to add it
});
Next, after I fill attb, I add all this to data list:
...
data.Add(new M2ArticleMain
{
Id = item.Id_Pk, //this is also from foreach loop,
Attribut_Web = attb //now in this part I have only data for Web_id and not Variants
}
Now my question is How to Add items later to data list to object Variants?
Something like this:
data.AddRange( "how to point to Variants" = some data);
The M2ArticleAttributeWeb type holding your Variants property is the member of a collection. That is, there are potentially many of them. You can reference an individual Variants property like this:
data[0].Attribut_Web[0].Variants
But you need to know which items you want to add map to which data and Attribut_Web indexes/objects in order to assign them properly. That probably means another loop, or even a nested loop. That is, you can see all of your Variants properties in a loop like this:
foreach(var main in data)
{
foreach(var attrw in main)
{
var v = attrw.Variants;
// do something with v
Console.WriteLine(v);
// **OR**
attrw.Variants = // assign some object
}
}
It's also much better practice to create your collection properties with the object, and then give them private set attributes:
public class M2ArticleMain
{
public int Id { get; set; }
public List<M2ArticleAttributeWeb> Attribut_Web { get; private set; } = new List<M2ArticleAttributeWeb>();
}
public class M2ArticleAttributeWeb
{
public int Web_Id { get; set; }
public M2ArticleTmpMainSkus Variants { get; set; }
}
public class M2ArticleTmpMainSkus
{
public DateTime TimeAdded { get; set; }
public List<string> Skus { get; private set; } = new List<string>();
}
Now instead of assigning Attribut_Web = attb, you would need to .Add() to the existing List.
This question already has answers here:
CS0120: An object reference is required for the nonstatic field, method, or property 'foo'
(9 answers)
Closed 3 years ago.
I am creating an application using Xamarin.Forms. I am trying to access each element in the list of MovieRent instances. I have a class that stores movie information:
public class MovieRent
{
public string movieTitle { get; set; }
public string movieReleaseDate { get; set; }
public int movieDuration { get; set; }
public double movieRentalPrice { get; set; }
public string movieRentType { get; set; }
public MovieRent(string mtitle, string mdate, int mtime, double mprice, string type)
{
movieTitle = mtitle;
movieReleaseDate = mdate;
movieDuration = mtime;
movieRentalPrice = mprice;
movieRentType = type;
}
}
addCartList is called to add a movie to a list. This creates/stores a list of movies.
class MoviesToRent
{
public List<MovieRent> movieRentList;
public MoviesToRent()
{
movieRentList = new List<MovieRent>();
}
public static MoviesToRent addCartList(string title, string date, int duration, double price, string type)
{
MoviesToRent movieList = new MoviesToRent();
MovieRentnewMovie = new MovieRent(title, date, duration, price, type);
movieList.movieRentList.Add(newMovie);
return movieList;
}
}
I am trying to access each instance, for example, the title of each movie in the list:
foreach (string movie in MoviesToRent.movieRentList)
{
this.Movie_Info.Text = movieRentList.title;
}
However, I get this error:
An object reference is required for the nonstatic field, method, or
property 'MoviesToRent.movieRentList'.
How can I overcome this error, so that I can access the movies that are in the list? I am trying display all movie info by looping through the list.
Thank you.
Your trying to access movieRentList as a static property. You need a instance of MoviesToRent and then access the list.
var movieRents = new MoviesToRent();
for (var movieRent in movieRents.movieRentList)
{
}
PS: In the example above, the list will be empty because I didnt add any object to it.
Okay, I think I first have to fix that naming and some glaring code issues. It is confusing the heck out of me:
public class Movie
{
public string movieTitle { get; set; }
public string movieReleaseDate { get; set; }
public int movieDuration { get; set; }
public double movieRentalPrice { get; set; }
public string movieRentType { get; set; }
public MovieRent(string mtitle, string mdate, int mtime, double mprice, string type)
{
movieTitle = mtitle;
movieReleaseDate = mdate;
movieDuration = mtime;
movieRentalPrice = mprice;
movieRentType = type;
}
}
class MoviesRentCart
{
public List<Movie> movieRentList;
public MoviesToRent()
{
movieRentList = new List<MovieRent>();
}
public static MoviesToRent addCartList(string title, string date, int duration, double price, string type)
{
//What does this line do here?
//MoviesToRent movieList = new MoviesToRent();
//fixed missing space
Movie newMovie = new Movie(title, date, duration, price, type);
movieList.movieRentList.Add(newMovie);
return movieList;
}
}
Then in your actuall code, you need a instance of MovieRentCart. Same way you make an instance of Movie. To that instance, you add the elements. Over that instance's movieRentList, you itterate.
The error happens because you're trying to access movieRentList as if it where a static field member of the class MoviesToRent. You need an instance of MoviesToRent like so:
var moviesToRent = new MoviesToRent();
And to access the title of each movie in the list do:
foreach (MovieRent movie in moviesToRent.movieRentList)
{
//The movie title is movie.movieTitle
}
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 4 years ago.
I have created a list names AllCalendarEventInfo inside which I have 2 more lists. when I am trying to add a list into the first index of the list, it throws IndexOutOfRangeException
model.AllCalendarEventInfo[i].allEventDates.Add(date);
model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);
in these two lines. please help.
heres my code :
var i = 0;
model.event_dates =
_iadminSettingsService.GetEventDatesByEventId(model.event_id);
foreach (var date in model.event_dates)
{
var addDate = date.event_date_start;
while (addDate >= date.event_date_start && addDate <= date.event_date_stop)
{
model.AllDateList.Add(new CalendarDates
{
Id = date.event_id,
Date = Convert.ToDateTime(addDate)
});
if (addDate.HasValue)
{
addDate = addDate.Value.AddDays(+1);
}
}
model.AllCalendarEventInfo[i].allEventDates.Add(date);
model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);
model.AllDateList.Clear();
i++;
}
here are all the models :
public class CalendarDates
{
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}",
ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
}
public class AllCalendarEventInfo
{
public AllCalendarEventInfo()
{
allCalendarDates = new List<CalendarDates>();
allEventDates = new List<event_dates>();
}
public List<CalendarDates> allCalendarDates { get; set; }
public List<event_dates> allEventDates { get; set; }
}
public class Event_ViewModel
{
public Event_ViewModel()
{
AllDateList = new List<CalendarDates>();
AllCalendarEventInfo = new List<AllCalendarEventInfo>();
}
public List<event_dates> event_dates { get; set; }
public List<event_dates> allEventDates { get; set; }
public List<CalendarDates> AllDateList { get; set; }
public List<AllCalendarEventInfo> AllCalendarEventInfo { get; set; }
}
You need to add a
new AllCalendarEventInfo
To the
model.AllCalendarEventInfo
before you try accessing it with an indexer. You are trying to access the first item in the list before you’ve even added anything to the list so the index is out of bounds.
So the code block after the while should start with
model.AllCalendarEventInfo.add(new AllCalendarEventInfo());
model.AllCalendarEventInfo[i].allEventDates.Add(date); model.AllCalendarEventInfo[i].allCalendarDates.AddRange(model.AllDateList);
model.AllDateList.Clear();
i++;
Sorry for the formatting, it’s from my phone
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to access referenced classes inside a main class and insert values into the objects. The classes are of partial type.
my code:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
public string ErrorMsg { get; set; }
public string Alpha2_Code { get; set; }
public string Digit3_Code { get; set; }
public string CountryName { get; set; }
public string IBAN_Mandatory { get; set; }
public As_SenderCountry[] As_SenderCountry { get; set; }
public As_ReceiverCountry[] As_ReceiverCountry { get; set; }
}
public partial class As_SenderCountry
{
public string SenderCountry_IsSensitive { get; set; }
}
public partial class As_ReceiverCountry
{
public string ReceiverCtry_EFTNotAllowed { get; set; }
public ReceiverCtry_AllowedCCY_Item[] ReceiverCtry_AllowedCCY_List { get; set; }
}
public partial class ReceiverCtry_AllowedCCY_Item
{
public string ReceiverCtry_AllowedCCY { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
//Get_CountryInfo_Resp.As_SenderCountry;
Get_CountryInfo_Resp.ReturnCode = dt.Rows[0]["column_Text"].ToString();
Get_CountryInfo_Resp.ErrorMsg = dt.Rows[1]["column_Text"].ToString();
Get_CountryInfo_Resp.Alpha2_Code = dt.Rows[2]["column_Text"].ToString();
Get_CountryInfo_Resp.Digit3_Code = dt.Rows[3]["column_Text"].ToString();
Get_CountryInfo_Resp.CountryName = dt.Rows[4]["column_Text"].ToString();
Get_CountryInfo_Resp.IBAN_Mandatory = dt.Rows[5]["column_Text"].ToString();
//GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive
I need to Insert dt.Rows[6]["column_Text"].ToString(); into the GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive .
How shall i proceed?
Please help.
Since As_SenderCountry is an array, it can contain multiple items. You have to assign an array too, not just a single instance.
I would start to create an object, add that to a list and eventually create an array out of it (or change the type to be a list instead of an array). You can also fix-size the array if you know the length already.
As_SenderCountry asc = new As_SenderCountry();
asc.SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
And then:
GetCountryInfo_Resp.As_SenderCountry = new As_SenderCountry[] { asc };
Or create the list, loop over items and eventually assign it:
List<As_SenderCountry> list = new List<As_SenderCountry>();
// some sort of loop
As_SenderCountry asc = new As_SenderCountry();
...
list.Add(asc);
// end loop
GetCountryInfo_Resp.As_SenderCountry = list.ToArray();
I don't think I fully understand your code, but As_SenderCountry and As_ReceiverCountry in your public partial class Get_CountryInfo_Resp_object are arrays, if I am not reading it wrong.
Therefore, the messy solution, if you know there is only one sender country:
GetCountryInfo_Resp.As_SenderCountry[0].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating. An example with your variables:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
...
public List<As_SenderCountry> As_SenderCountry { get; set; }
public List<As_ReceiverCountry> As_ReceiverCountry { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
...
GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive.Add(dt.Rows[6]["column_Text"].ToString());
p.s. Your variable and class naming is very messy. I would suggest you to clean that up so that you, as well as the people reading the question can understand it better.
You need to create a new instance of the inner class as you would do normally for any other class, and then assign whatever value to the field you need.
First you need to assign the length of the array, then each cell of the array will contain an instance of an object of type (As_SenderCountry ), then you should assign each object the value you need.
GetCountryInfo_Resp.As_SenderCountry = new GetCountryInfo_Resp.As_SenderCountry();
GetCountryInfo_Resp.As_SenderCountry[INDEX_HERE].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
This question already has answers here:
Getting ALL the properties of an object [duplicate]
(6 answers)
Closed 8 years ago.
I've inherited from PictureBox and I have a lot of custom Properties set in place. One thing that I've grown intolerant of lately is the fact that I must always specify manually, each and every Property that I wish to output to the Console (to see its value, if any).
An example:
public class Picture : PictureBox
{
public int Id { get; set; }
public class PictureProperties
{
public string Name { get; set; }
public string Extension { get; set; }
public string Credits { get; set; }
public Size DesignTimeSize { get; set; }
public Point DesignTimePoint { get; set; }
}
public PictureProperties Properties { get; set; }
}
Usage:
public void test()
{
SortedList<int, JTS.Picture> list = new SortedList<int, JTS.Picture>();
for(int i = 0; i < 10; i++)
{
list.Add(1, new Picture()
{
Id = 1,
Properties = new Picture.PictureProperties()
{
Name = "Travis",
Credits = "people here"
},
Thumbnail = new Picture.PictureThumbnail()
{
Size = new Size(250, 250)
}
});
}
}
What I would like to do is, inside that foreach loop:
Console.WriteLine(Picture); and it will automagically output all of the properties contained within the Picture control. i.e. Name, Id, PictureProperties and its properties, Size, Location, absolutely everything. If you type, myNewPicture. intellisense will give you a list of all properties. That's what I want. All of that. In the console (or in a variable/string to output to file).
Is there a way to do this?
yes you can. You have 2 options:
1: override your object's ToString() method to output the properties you want to show
2: Take a look at Reflection. Here's another question that is the same with an answer on it:
c# getting ALL the properties of an object