Access Each Class Element In C# [duplicate] - c#

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
}

Related

Accept a list of objects from form data in ASP.NET Core

I am currently struggling to accept a list of objects from FormData in ASP.NET Core.
The project looks like this:
I have a class called Stavka (English: Item).
public class Stavka
{
public string naziv { get; set; }
public double cenaPoJedinici { get; set; }
public string jedinicaMere { get; set; }
public int kolicina { get; set; }
public Stavka(string naziv, double cenaPoJedinici, string jedinicaMere, int kolicina)
{
this.naziv = naziv;
this.cenaPoJedinici = cenaPoJedinici;
this.jedinicaMere = jedinicaMere;
this.kolicina = kolicina;
}
public Stavka()
{
}
}
I have a class called Faktura (English: Bill) which has a variable called Stavke (English: Items) that is a list containing the Stavka objects.
public class Faktura
{
public int Id { get; set; }
public string pibStart { get; set; }
public string pibEnd { get; set; }
public DateTime datumGen { get; set; }
public DateTime datumRok { get; set; }
public List<Stavka> stavke { get; set;}
public double cena { get; set; }
public string tip { get; set; }
public Faktura(int id, string pibStart, string pibEnd, DateTime datumGen, DateTime datumRok, List<Stavka> stavke, string tip)
{
Id = id;
this.pibStart = pibStart;
this.pibEnd = pibEnd;
this.datumGen = datumGen;
this.datumRok = datumRok;
this.stavke = stavke;
this.tip = tip;
double sumCena = 0;
foreach(Stavka s in stavke)
{
sumCena += s.kolicina * s.cenaPoJedinici;
}
this.cena = sumCena;
}
public Faktura()
{
}
I want to create a new Faktura object and add it to a list within my Controller. I tried to do this with the following code:
[HttpPost("dodajFakturu")]
public IActionResult dodajFakturu([FromForm]string pibStart, [FromForm]string pibEnd,[FromForm]DateTime datumStart, [FromForm]DateTime datumEnd,[FromForm]List<Stavka> stavkeLis, [FromForm]string tip)
{
int id = lst.OrderByDescending(p => p.Id).First().Id + 1;
Faktura f = new Faktura(id, pibStart,pibEnd, datumStart,datumEnd,stavkeLis,tip);
lst.Add(f);
return Ok(SveFakture());
}
And yet, when i post the request (in Swagger/Postman), the variable stavkeLis (which accepts the JSON array) is always empty:
This is certainly because i fundamentally misunderstood the way in which NET Core accepts these variables.
Is there some other way to send a list of objects through form data?
this way you have is currect, but if its not maybe because simple code problem but way that you right the code can be better or you can say develop your code as Below:
// StavkaBody => I Mean All Body In One Json
public async Task<IActionResult> MethodName([FromForm] string
StavkaBody)
{
YourObjectType object = new YourObjectType();
// this will be Populate All Json To Single object And
// You dont Need To Add some Constructors For Done this
JsonConvert.PopulateObject(StavkaBody, objec);
// Example Usage
Console.WriteLine(object.Name);
}
in Here I`ve Used The Newtonsoft.Json For this And Its Make Your Model So Much Simpler.
I Hope Its Helps

Add values to list in class c# [duplicate]

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

Create object of type specified in a string

I have a bunch of classes generated by EF that are simple tables and have similar structures:
public class Contact
{
public int ID { get; set; }
public string Description { get; set; }
}
public class Member
{
public int ID { get; set; }
public string Description { get; set; }
}
I've also got a method for returning an object of a specified type:
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
What I want to do is something like this:
public ActionResult GetAll(string ClassType) // ClassType will be the name of one of the classes above
{
Object LookupType = GetInstance<Object>(ClassType);
List<LookupType> AllList = new List<LookupType>();
AllList = repo.GetAll<LookupType>().ToList<LookupType>(); // some generic method that will return a list;
}
This makes the compiler mad because I'm using a variable (LookupType) rather than a true type to build the list. However, neither of these work either:
List<LookupType.GetType()> Items = new List<LookupType.GetType()>();
List<typeof(LookupType)> Items = new List<typeof(LookupType)>();
Both cause an error - "Using generic type List requires 1 type argument".
Is there a proper way to do this? Is there a way to convert ClassType directly to a type without first making it an object (from which I hope to derive the type)?
Try using the CreateInstance method
SomeObject someObject = new SomeObject();
Type type = someObject.GetType();
Type listType = typeof(List<>).MakeGenericType(new [] { type });
IList list = (IList)Activator.CreateInstance(listType);
You cannot do it with C#!!
Compiler must to know the parameter type.
In that maybe you would like to accomplish, interfaces will help you
public class Contact: IIdDescription
{
public int ID { get; set; }
public string Description { get; set; }
}
public class Member: IIdDescription
{
public int ID { get; set; }
public string Description { get; set; }
}
public interface IIdDescription
{
int ID { get; set; }
string Description { get; set; }
}
public ActionResult GetAll(string type)
{
var AllList = new List<IIdDescription>();
if(type == Member.GetType().Name)
AllList = repo.Set<Member>().Cast<IIdDescription >().ToList();
if(type == Contact.GetType().Name)
AllList = repo.Set<Contact>().Cast<IIdDescription >().ToList();
...
}
and into your view use interface as model, something like
#model IEnumerable<IIdDescription>
If you don't know the type ahead of time maybe using a list of dynamic objects can help.
var item = GetInstance<Contact>("Namespace.Contact");
var items = new List<dynamic>();
items.Add(item);
You can then access the types like so...
Contact contact = items[0];
Just be aware that using dynamic can be expensive.

c# get all properties in classProperty

I have a List and I would like to know how much Properties are in each Item List.
Like the following example code I got four 'items' String in my Property class and I want to add it to a listview.
The problem is that I can't enumerate my property class Items as they are not a list. so I would like to count String Items in Property and then increment a variable to add it to the listview.
The main point is that my properties can be of any type (String, int and so on) and I would like to do a generic code for that.
Thanks in advance.
Code classList
public static class mylistitems
{
// public static List<Properties> mylistprop = new List<Properties>();
public static List<Properties> createdata(String name, String surname, String friend, String pet)
{
var DataProperties = new List<Properties>();
DataProperties.Add(new Properties { Name = name, SurName = surname, Friend = friend, Pet = pet });
return DataProperties;
}
public class Properties
{
public String Name { get; set; }
public String SurName { get; set; }
public String Friend { get; set; }
public String Pet { get; set; }
}
}
Code Caller
List<mylistitems.Properties> newlistitem = mylistitems.createdata("Derrick","Thomas","giordino","Max");
foreach (mylistitems.Properties propertyitem in newlistitem)
{
//Here!! Is it possible to get all the properties in a loop
ListViewItem LVitem = new ListViewItem();
LVitem.SubItems.Add(propertyitem.Name);
LVitem.SubItems.Add(propertyitem.SurName);
LVitem.SubItems.Add(propertyitem.Friend);
LVitem.SubItems.Add(propertyitem.Pet);
//how to change it like something like this
foreach (String item in propertyitem)
{ LVitem.SubItems.Add(item); }
}

Match String version of Object element to Object element itself

I'm having an instance where I have an object that looks similar to this:
public class answerObject
{
public string Q1 { get; set; }
public string Q2 { get; set; }
public string Q3 { get; set; }
public string Q4 { get; set; }
public string Q5 { get; set; }
...
public string Q80 { get; set; }
}
The questions themselves look like this:
public class questionObject
{
public string DataMember { get; set; }
...
}
The DataMember string carries a string version of the answer object element. So, if I have question 1 have a datamember of "Q1" then I want it to fill in answerObject.Q1 and so on. Right now I have a lengthy switch statement to solve this, but there has to be a more efficient way to do this.
switch(DataMember) {
case "Q1":
answerObject.Q1 = answerValue;
break;
case "Q2":
answerObject.Q2 = answerValue;
break;
....
};
I've researched for a few hours and didn't come up with anything. Any help is much appreciated.
You can use Reflection for that but I would keep using the switch/case:
var property = typeof(answerObject).GetProperty(DataMember);
if(property != null) property.SetValue(yourInstance, answerValue);
After your edit using Reflection makes more sense.Anyway you can also put this code into an extension method:
public static void SetAnswer(this answerObject instance, string question, string value)
{
var property = typeof(answerObject).GetProperty(question);
if (property != null) property.SetValue(instance, value);
else { // throw exception or display a message }
}
A possible solution is to use a Dictionary object - make your Questions a dictionary and set the string Q1, Q2, etc. as key (your DataMember would later be filled with one of the keys). Then to assign the question just use the already set DataMember and the item property of the Dictionary object. The code could look like this:
public class QuestionObject
{
public string DataMember { get; set; }
public String Answer { get; set; }
}
public class AnswerObject
{
public Dictionary<String, String> Questions { get; set; }
public AnswerObject()
{
Questions = new Dictionary<String, String>();
// init the question keys
Enumerable.Range(1, 80).ToList().ForEach(index =>
{
Questions.Add(String.Format("Q{0}", index), String.Empty);
});
}
}
And the usage looks like this:
var question = new QuestionObject();
var answer = new AnswerObject();
question.DataMember = #"Q75";
// set the question = the same as the switch/case
answer.Questions[question.DataMember] = #"and the answer is ...";

Categories