This question already has answers here:
WriteLine with a class
(9 answers)
Print out object elements from list [duplicate]
(2 answers)
Print List of objects to Console
(3 answers)
Class List Keeps Printing Out As Class Name In Console?
(4 answers)
Why / when would it be appropriate to override ToString?
(17 answers)
Closed 2 years ago.
I'm trying to create an ArrayList with cars I've created using a constructor class and then afterwards use a foreach loops to then print the model name of each cars.
I've created the car objects as following
Car car1 = new Car("Audi e-tron", "Black", 2021);
Car car2 = new Car("Audi RS7", "Black", 2021);
Car car3 = new Car("Audi A5", "Black", 2021);
I created the ArrayList and attempted to begin adding the car objects to the ArrayList
ArrayList carList = new ArrayList();
carList.Add(car1);
carList.Add(car2);
carList.Add(car3);
I tested to see if the code was working properly up to this point and checked if the ArrayList has populated
Console.WriteLine("car list: {0}", carList[0]);
but that returns
ArrayListPractice.MainClass+Car
How can I add objects from the constructor to the ArrayList and return a parameter of the object? Thank you!
What exactly are you trying to print in the code block below?
Console.WriteLine("car list: {0}", carList[0]);
If you want to print the string property you passed into the constructor of the first element ("Audi e-tron"), for example, try this:
Console.WriteLine("car list: {0}", carList[0].Name); // 'Name' should be the field name you're looking for
You should override the Car object, ToString() method and there is no need to other considerations, it will be automatically done
Related
This question already has answers here:
Print out object elements from list [duplicate]
(2 answers)
Print List of objects to Console
(3 answers)
print list<object> in console c# [duplicate]
(2 answers)
Closed 2 years ago.
I'm learning to code. I have started a little project where I design a text-based RPG.
I am struggling with storing and retrieving objects in and from an array.
Please have a look at my progress so far and tell me what I am doing wrong.
If I am using a wrong approach please also let me know how to do the whole thing smarter :)
First I define some properties of the player:
static class Globals
{
public static string playername;
...
public static object[] playerInventory = new object[4];
}
Then I create the weapon class:
public class Weapon
{
public string weaponName;
public int weaponBaseDamage;
public Weapon(string name, int baseDamage)
{
weaponName = name;
weaponBaseDamage = baseDamage;
}
Then I create the first basic weapon and try to store it in an array.
public class Program
{
public static void Main()
{
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
The unexpected result of the second WriteLine command tells me that something must be quite wrong, but I don't know what it is and how to fix it. Any advice is welcome! (And please keep in mind that I am new to Coding).
It's required Typecasting. Please try like below:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName)
Ok, lets look at what your code does:
Weapon StartSword = new Weapon("My first Sword", 1);
Globals.playerInventory[0] = StartSword;
Console.WriteLine(StartSword.weaponName); // This works
Above you create an object of the type Weapon with the name "My first Sword". And then print the name of that public property that is populated in the constructor.
Console.WriteLine(Globals.playerInventory[0]); // This prints "CSharp_Shell.Weapon", but I expected "StartSword"
Here you try to write an object. But an object is not a string so c# will automatically try to convert that to a string and will look at the type. So it is expected that it will not write the properties but a representation of the type.
Console.WriteLine(Globals.playerInventory[0].weaponName); // This results in an Error
Globals.playerInventory is defined as object[] playerInventory, so even if we know that you have entered an object of type weapon there, we need to specify that. Either by letting playerInventory be of the type Weapon[] playerInventory, or by type casting your object before using its properties, like this:
Console.WriteLine(((Weapon)Globals.playerInventory[0]).weaponName);
This question already has answers here:
Method to check array list containing specific string
(4 answers)
Closed 3 years ago.
I got an ArrayList in C#
ArrayList myAL = new ArrayList();
now I add a string to it
myAL.Add("Hello");
How can I now figure out if the String "Hello" exist in the array. I know it's possible to loop over it, but I think there must exist a function or something.
You can simply use the method Contains from System.Collections
Microsoft Doc - Contains
For your example :
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
if (myAL.Contains("Hello"))
{
// Do something
}
This question already has answers here:
Initializing collections that contain nested collections
(3 answers)
Closed 6 years ago.
I have to make two lists in C # . How do the second list ?
The first is well and works , the second already tried as exemplified below but does not work . And I want it to be exactly like or similar without the use of other variables
List<String> t = new List<string>() {"question","anotherQuestion"};
then i want another list
and i would like to initialize it like this.
List<String[]> t = new List<string[]>()
{
("rightawnser","wrongAwnser"), //1st question
("rightawnser","wrongAwnser"), //2nd question
};
Close, but you have to create an array for each list entry:
List<string[]> t = new List<string[]>()
{
new[] { "rightawnser","wrongAwnser" }, //1st question
new[] { "rightawnser","wrongAwnser" }, //2nd question
};
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have one class where in I am defining 2 variables.
public class attachment_type
{
string filename;
int cnt;
}
In the 2nd class, I want to assign string value to filename. In already existing code they have made array of class type.
public class mainApp
{
attachment_type[] at = new attachment_type[dt.rows.count];
at[0].filename = "test File"
}
I am not able to do the above. Error comes at line at[0].filename = "test File";
Object reference not set to an instance of object.
You have to assign a new instance of your class for every entry in the array:
public class mainApp
{
attachment_type[] at = new attachment_type[dt.rows.count];
at[0] = new attachment_type();
at[0].filename = "test File"
}
With attachment_type[] at = new attachment_type[dt.rows.count]; you only allocate a new array of a given size, however the array does not have any content so far. You only say that you need some memory, but not for what.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
i am very new to C# programming so my question may sound very silly
actualy i am creating an multidimensional string array like
public class master
{
public List<string> user_selected = new List<string>();
public List<string> available = new List<string>();
public List<string> bookedseats = new List<string>();
public string [] [] trackbooked=new string[30][] ;
}
now i am assigning some values to it like
a[l].trackbooked[i][j] = pb.Name;
a is a list of object
List<master> a = new List<master>();
a.Add(obj0);
a.Add(obj1);
a.Add(obj2);
a.Add(obj3);
a.Add(obj4);
can some one plz help.thank u in adv.
You've only initialized one dimension of your multidimensional array. See msdn for all the ways you can initialize a multidimensional array.
public string [,] trackbooked=new string[30,30] ;
pb.Name.Tostring();
I would venture to guess that whatever pb is that its NAME value isn't returned as a string. You should be able to use the above command to correct your issue.