C
C#ā€¢14mo ago
sebt

ā” C# Arrays/Switch case help

Hi guys, I was just wondering if anybody here would be willing to potentially message me or hop in a voice call if they know a solution to my issue. The issue is as follows: Basically, I currently have a menu system that asks the user for an input, I then have a 2D array consisting of information that will be displayed depending on the user's input, However, I am currently using a switch case like case "1" do this, case "2" do that, and this approach is for 8 different scenarios and thus is around 160lines long of just repeated console.writeline jargon. Since the user input is equal to one of the elements of the array, I was wondering if there was a shorter way of writing this so that my code would detect the user input, match that to its corresponding element in the array, and then print every element of said array. If anybody could think of a solution and help me I would seriously appreciate it.
164 Replies
mtreit
mtreitā€¢14mo ago
I think if you provide a small minimal code sample that illustrates what you are currently doing it will be easier for people to suggest a better way, if one exists.
sebt
sebtOPā€¢14mo ago
and then it just goes on like that for every planet name when it is inputted,
No description
No description
No description
mtreit
mtreitā€¢14mo ago
Use $code to share code samples, those screenshots are pain
MODiX
MODiXā€¢14mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
sebt
sebtOPā€¢14mo ago
$code
MODiX
MODiXā€¢14mo ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
sebt
sebtOPā€¢14mo ago
ok shall i send my whole code there isnt much more really or do u want the same snippets from the ss
mtreit
mtreitā€¢14mo ago
When you have repeated code like that that only changes slightly, you should turn it into a function (method) so you can re-use it. Sure, send the entire code I'm not sure a 2D array is a very good choice of data structure.
sebt
sebtOPā€¢14mo ago
cs
cs
sebt
sebtOPā€¢14mo ago
oh how come what do u suggest
mtreit
mtreitā€¢14mo ago
Use $paste
MODiX
MODiXā€¢14mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
sebt
sebtOPā€¢14mo ago
BlazeBin - sragjyveqzdp
A tool for sharing your source code with the world!
mtreit
mtreitā€¢14mo ago
Hard coding array indexes like that is a very fragile way to approach things.
sebt
sebtOPā€¢14mo ago
hmm how else do u reckon i should store that info then? but i cant read or write to a file btw so storing it in a file isnt an option
Pobiega
Pobiegaā€¢14mo ago
You seem to know how to create classes. Have you considered making a class that holds planetary data, then instantiating that class once per planet?
sebt
sebtOPā€¢14mo ago
so like make an entirely seperate class just for the planetary data and then depending on user input, displaying the corresponding section of that class that will show the right data?
mtreit
mtreitā€¢14mo ago
You can use a dictionary to lookup the planet based on the user input
record Planet(string Name, double Mass, int Distance, int NumberOfMoons);
record Planet(string Name, double Mass, int Distance, int NumberOfMoons);
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0) },
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)}
// etc.
};
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0) },
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)}
// etc.
};
sebt
sebtOPā€¢14mo ago
i see
mtreit
mtreitā€¢14mo ago
(You could also just use strings if it suits your purpose rather than actual types, but in a real world application where you are representing something like the mass of a planet you should probably use numeric types so you can do comparisons and calculations.)
sebt
sebtOPā€¢14mo ago
yeah i want them to be the 'correct' data type
Pobiega
Pobiegaā€¢14mo ago
Well, see if you can implement mtreits suggestion then if you get stuck, tell us where and how
sebt
sebtOPā€¢14mo ago
i have never used dictionaries before so this will be good practice then
Pobiega
Pobiegaā€¢14mo ago
yep! its a lookup table, one key for one value
mtreit
mtreitā€¢14mo ago
Also in a real world application you would probably have a Moon type and then instead of NumberOfMoons the planet would have a List of Moon objects with things like the mass of the moon, etc., although that's perhaps going too far down the rabbit hole for this particular program / assignment.
sebt
sebtOPā€¢14mo ago
yeah but the problem with that was some planets have like 40 moons so its a lot of data so i chose to do number
Pobiega
Pobiegaā€¢14mo ago
40? rookie numbers šŸ˜„
sebt
sebtOPā€¢14mo ago
and then if user queries data i would display some of the more promeneint moons i suppoes haha
Pobiega
Pobiegaā€¢14mo ago
Jupiter has a varying number of moons, iirc between 90 and 104 or something
sebt
sebtOPā€¢14mo ago
yeah something like that ok guys thanks for the advice, i will try change the program now and use a dictionary to see how this makes things
mtreit
mtreitā€¢14mo ago
Also, functions are your friend!
sebt
sebtOPā€¢14mo ago
just to check, is PlanetInfo() an example of a function or is that a method
mtreit
mtreitā€¢14mo ago
For instance, in your original example:
Console.WriteLine(planetArray[0, arrayNumber]);
Console.WriteLine(planetArray[0, arrayNumber]);
This is opaque (not immediately clear what it's doing) and repeated many times, so a better approach would have been to write a small helper function:
void PrintHeader()
{
Console.WriteLine("Planet Name:", "Planetary Mass:", "Distance from sun:", "No. Moons");
}
void PrintHeader()
{
Console.WriteLine("Planet Name:", "Planetary Mass:", "Distance from sun:", "No. Moons");
}
Functions and methods are the same thing in C#
sebt
sebtOPā€¢14mo ago
ah ok
mtreit
mtreitā€¢14mo ago
Function is just the more general programming term.
sebt
sebtOPā€¢14mo ago
gotcha
mtreit
mtreitā€¢14mo ago
Method is basically a function associated with an object and/or type.
sebt
sebtOPā€¢14mo ago
so here are u saying i should make a helper function that will output the header above each piece of data, rather than using the Console.WriteLine(planetArray[0, arrayNumber]); idea
mtreit
mtreitā€¢14mo ago
Yes, then when you see this in the code:
PrintHeader();
PrintHeader();
...it's more clear what that line of code is doing. In this case you're only saving a single line of code but in fact your could use the same technique for other places where you are doing the same thing repeatedly.
sebt
sebtOPā€¢14mo ago
nice thank you i will implement that
mtreit
mtreitā€¢14mo ago
@sebt for the sake of argument let's say you wanted to keep your original 2D array implementation. Consider how much easier something like this would be to read than your original code...
public static string DisplayPlanetInfo(string input)
{
switch (input)
{
case "mercury":
PrintPlanetInfo(1);
break;
case "venus":
PrintPlanetInfo(2);
break;
case "earth":
PrintPlanetInfo(3);
break;
case "mars":
PrintPlanetInfo(4);
break;
case "jupiter":
PrintPlanetInfo(5);
break;
case "saturn":
PrintPlanetInfo(6);
break;
case "uranus":
PrintPlanetInfo(7);
break;
case "neptune":
PrintPlanetInfo(8);
break;
default:
Console.WriteLine($"Sorry, I don't recognize the planet '{input}'.");
break;
}

return input;
}
public static string DisplayPlanetInfo(string input)
{
switch (input)
{
case "mercury":
PrintPlanetInfo(1);
break;
case "venus":
PrintPlanetInfo(2);
break;
case "earth":
PrintPlanetInfo(3);
break;
case "mars":
PrintPlanetInfo(4);
break;
case "jupiter":
PrintPlanetInfo(5);
break;
case "saturn":
PrintPlanetInfo(6);
break;
case "uranus":
PrintPlanetInfo(7);
break;
case "neptune":
PrintPlanetInfo(8);
break;
default:
Console.WriteLine($"Sorry, I don't recognize the planet '{input}'.");
break;
}

return input;
}
That's where encapsulating code into methods starts to help...
sebt
sebtOPā€¢14mo ago
what is the deal with the $ sign in the default consolewriteline i see it a lot but dont know what it actually does
Angius
Angiusā€¢14mo ago
$interpolation
MODiX
MODiXā€¢14mo ago
String interpolation is the preferred way of building strings in C#. It is easier to read than concatenation. For example:
var foo = 1;
var bar = 2;
Console.WriteLine("foo is equal to: " + foo + " and bar is equal to: " + bar);
var foo = 1;
var bar = 2;
Console.WriteLine("foo is equal to: " + foo + " and bar is equal to: " + bar);
can be written as:
var foo = 1;
var bar = 2;
Console.WriteLine($"foo is equal to: {foo} and bar is equal to: {bar}");
var foo = 1;
var bar = 2;
Console.WriteLine($"foo is equal to: {foo} and bar is equal to: {bar}");
sebt
sebtOPā€¢14mo ago
thank you haha so when the $ sign is htere it lets the code know that some interpolation is gonna go down
mtreit
mtreitā€¢14mo ago
Technically you can put the $ and not include anything to actually interpolate, in which case it's sort of pointless but it's technically allowed.
sebt
sebtOPā€¢14mo ago
but you cant interpolate without the $ right>
mtreit
mtreitā€¢14mo ago
Correct
sebt
sebtOPā€¢14mo ago
nice
mtreit
mtreitā€¢14mo ago
The $ tells the compiler to do the string interpolation, just in case it's not clear.
sebt
sebtOPā€¢14mo ago
yhyh ive just tried implementing a helper function along with a switch case whilst still using the 2d array idea i think im just gonna go with dictionaries lool
mtreit
mtreitā€¢14mo ago
I use dictionaries constantly. I've never used a 2D array at work.
sebt
sebtOPā€¢14mo ago
oh damn
mtreit
mtreitā€¢14mo ago
I guess they are helpful if you are representing things like a matrix or a grid for a game or something but the kind of work I do doesn't involve that kind of thing. I think the first time I used a 2D array was last year during AdventOfCode.
nohopestage
nohopestageā€¢14mo ago
Why not create a Planet class?
sebt
sebtOPā€¢14mo ago
well i had actually only used 1d arrays so i wanted to try with 2d arrays for this application what do u mean create a planet class to hold all information?
MODiX
MODiXā€¢14mo ago
mtreit
record Planet(string Name, double Mass, int Distance, int NumberOfMoons);
record Planet(string Name, double Mass, int Distance, int NumberOfMoons);
Quoted by
<@406536255426396160> from #C# Arrays/Switch case help (click here)
React with āŒ to remove this embed.
sebt
sebtOPā€¢14mo ago
what is record ive never seen it before
mtreit
mtreitā€¢14mo ago
(records are just classes but with some stuff auto-implemented for you.)
sebt
sebtOPā€¢14mo ago
oh haha
mtreit
mtreitā€¢14mo ago
If you have types that just hold data, records are nice and succinct.
nohopestage
nohopestageā€¢14mo ago
True, I often forget they exist as I'm used to classes
sebt
sebtOPā€¢14mo ago
ok i will use record then for this
mtreit
mtreitā€¢14mo ago
SharpLab
C#/VB/F# compiler playground.
sebt
sebtOPā€¢14mo ago
i have no idea what im looking ath haha ahh so with record i have the things like no. moons, planet name, mass etc all defined already with the correct data types so when it comes to implementing in the dictionary it already knows what data type each thing is and what it actually represents and thats also why its better to use dictionaries than arrays dictionaries are cool bro
Angius
Angiusā€¢14mo ago
Well, you can have an array of planets as well
mtreit
mtreitā€¢14mo ago
Dictionaries give you a nice way to fetch a given record by some key.
sebt
sebtOPā€¢14mo ago
so much nicer
Angius
Angiusā€¢14mo ago
Planet[]
sebt
sebtOPā€¢14mo ago
but dictionaries make retreiving data nicer than arrays it seems
Angius
Angiusā€¢14mo ago
In some cases, yes
sebt
sebtOPā€¢14mo ago
in this case i mean
Angius
Angiusā€¢14mo ago
Dictionaries can have (mostly) anything be the key So, yes You can get allPlanets["jupiter"] for example While with an array you would have to somehow remember, or print it to the user, that Jupiter is stored at index 7 or so Unless... you were to use LINQ allPlanets.Where(planet => planet.Name == "jupiter").Single() for example
sebt
sebtOPā€¢14mo ago
what is LInq
mtreit
mtreitā€¢14mo ago
banblob
sebt
sebtOPā€¢14mo ago
I See it mentioned a lot did i just commit a sin by asking that
nohopestage
nohopestageā€¢14mo ago
Could also just have a Single with a predicate I believe
mtreit
mtreitā€¢14mo ago
No, @ZZZZZZZZZZZZZZZZZZZZZZZZZ commited a sin by writing that code.
sebt
sebtOPā€¢14mo ago
oh ok
Angius
Angiusā€¢14mo ago
Right, true. My EF habits are showing lol, I like the condition to always be first
mtreit
mtreitā€¢14mo ago
(linear search to look things up in a list or array is very slow compared to using a dictionary, which has constant time lookup) LINQ has it's uses but using it to look things up in a list is generally not one of it's better use cases.
sebt
sebtOPā€¢14mo ago
ok im gonna pretend it doesnt exist then for now
mtreit
mtreitā€¢14mo ago
No description
sebt
sebtOPā€¢14mo ago
yeah but the difference is minimal no? nano seconds!
mtreit
mtreitā€¢14mo ago
If you call 4,000 times slower minimal
sebt
sebtOPā€¢14mo ago
yeah thats true but if u had them both side by side i dont think i could honestly tell if its in nanoseconds
mtreit
mtreitā€¢14mo ago
500 million nanoseconds is half a second
sebt
sebtOPā€¢14mo ago
yo im just making this dictionary now and for some of the planets the distance is billion rather than million km away and im getting an error saying cannot convert from long to int shall i change distance from int to long then
mtreit
mtreitā€¢14mo ago
int is limited to 2^32 or a little over 4 billion. If you need numbers larger than that, you want a 64-bit integer instead of a 32-bit integer. (long is the C# name for a 64-bit integer.)
sebt
sebtOPā€¢14mo ago
yeah
Angius
Angiusā€¢14mo ago
Could always try using an uint
sebt
sebtOPā€¢14mo ago
ive never had to use such big numbers before thats why i was unfamilar with it but yeah im gonna use long rather than int because i need to
Angius
Angiusā€¢14mo ago
But, yeah, long will probably be safer
mtreit
mtreitā€¢14mo ago
That's still limited to 4 billion (int is actually limited to 2 billion since it's signed.)
sebt
sebtOPā€¢14mo ago
really my value is > 4 bil and im not getting an error
Angius
Angiusā€¢14mo ago
long it is
MODiX
MODiXā€¢14mo ago
Angius
REPL Result: Success
new {
@int = int.MaxValue,
@uint = uint.MaxValue,
@long = long.MaxValue,
@ulong = ulong.MaxValue,
}
new {
@int = int.MaxValue,
@uint = uint.MaxValue,
@long = long.MaxValue,
@ulong = ulong.MaxValue,
}
Result: <>f__AnonymousType0#1<int, uint, long, ulong>
{
"int": 2147483647,
"uint": 4294967295,
"long": 9223372036854775807,
"ulong": 18446744073709551615
}
{
"int": 2147483647,
"uint": 4294967295,
"long": 9223372036854775807,
"ulong": 18446744073709551615
}
Compile: 499.957ms | Execution: 119.831ms | React with āŒ to remove this embed.
sebt
sebtOPā€¢14mo ago
wow ah i see wow ulong is huge
mtreit
mtreitā€¢14mo ago
18 quintillion...
sebt
sebtOPā€¢14mo ago
hmm i made a dictionary and put it within a record
record Planet(string Name, double Mass, long Distance, int NumberOfMoons)
{
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0)},
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)},
{ "earth", new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)},
{ "mars", new Planet("Mars", 6.4171 * Math.Pow(10, 23), 235_610_000, 2)},
{ "jupiter", new Planet("Jupiter", 1.8982 * Math.Pow(10, 27), 743_830_000, 95)},
{ "saturn", new Planet("Saturn", 5.6834 * Math.Pow(10, 26), 1_458_000_000, 146)},
{ "uranus", new Planet("Uranus", 8.6810 * Math.Pow(10, 25), 2_934_600_000, 27)},
{ "neptune", new Planet("Neptune", 1.0241 * Math.Pow(10, 26), 4_472_700_000, 14)},
};
}
record Planet(string Name, double Mass, long Distance, int NumberOfMoons)
{
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0)},
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)},
{ "earth", new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)},
{ "mars", new Planet("Mars", 6.4171 * Math.Pow(10, 23), 235_610_000, 2)},
{ "jupiter", new Planet("Jupiter", 1.8982 * Math.Pow(10, 27), 743_830_000, 95)},
{ "saturn", new Planet("Saturn", 5.6834 * Math.Pow(10, 26), 1_458_000_000, 146)},
{ "uranus", new Planet("Uranus", 8.6810 * Math.Pow(10, 25), 2_934_600_000, 27)},
{ "neptune", new Planet("Neptune", 1.0241 * Math.Pow(10, 26), 4_472_700_000, 14)},
};
}
but i dont know how to access elements of it based upon userinput
mtreit
mtreitā€¢14mo ago
Don't put the dictionary inside the record
sebt
sebtOPā€¢14mo ago
is that because i will have trouble accessing it
Angius
Angiusā€¢14mo ago
That And because there's no reason to do that
mtreit
mtreitā€¢14mo ago
Well, no, but...you're creating a copy of that dictionary inside every planet.
Angius
Angiusā€¢14mo ago
And because you create a cyclical dependency
mtreit
mtreitā€¢14mo ago
That's just wasting memory
sebt
sebtOPā€¢14mo ago
ah ok whats the point of the record then is that where i should put a method for accesing the elements within the dictionary?
Angius
Angiusā€¢14mo ago
No The point is to group up all the properties of the planet It's the basis of any object-oriented programming language Objects
sebt
sebtOPā€¢14mo ago
hmm ok so where do u think is best to store the dictionary
mtreit
mtreitā€¢14mo ago
In programming you have data and code that operates on data. Records (classes) are how you define data in a structured way. You can just make the dictionary a static field of your class like you did with the array you were using previously.
sebt
sebtOPā€¢14mo ago
ah ok
mtreit
mtreitā€¢14mo ago
Or put it in it's own class... Lots of ways to organize things.
sebt
sebtOPā€¢14mo ago
i think i prefer to put it in its own class yeah thats ive done i put the dictionary in its own class so now how do i access elements from the dictionary in a way that uses less lines of code than before when i incorporated the array? and display to the user
Angius
Angiusā€¢14mo ago
theDictionary[key]
sebt
sebtOPā€¢14mo ago
i cant access it
Angius
Angiusā€¢14mo ago
Why?
sebt
sebtOPā€¢14mo ago
so lets say i just try output it with a console write lien when i type the name of the dictionary which is planetInfo it says not defined in current context
Angius
Angiusā€¢14mo ago
Well... is it defined in the current context? $scopes
MODiX
MODiXā€¢14mo ago
scope A {
thing a;
scope B {
thing b;
}
}
scope A {
thing a;
scope B {
thing b;
}
}
thing a is available in scope A and scope B thing b is available only in scope B
sebt
sebtOPā€¢14mo ago
yeah i think so i cant see why it is having problems accessing it
mtreit
mtreitā€¢14mo ago
@sebt show your latest code
sebt
sebtOPā€¢14mo ago
ok but ofc it is very wip
mtreit
mtreitā€¢14mo ago
You probably didn't make it public or something.
sebt
sebtOPā€¢14mo ago
BlazeBin - dumealmqqfkb
A tool for sharing your source code with the world!
mtreit
mtreitā€¢14mo ago
public class PlanetData
{
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
public class PlanetData
{
Dictionary<string, Planet> planetInfo = new Dictionary<string, Planet>
Yeah the planetInfo field is not public. Also, you should make it a property not a field.
sebt
sebtOPā€¢14mo ago
how do i do that also i tried making public but vs said its 'inconsistent accessibility' and gave an error
mtreit
mtreitā€¢14mo ago
public record Planet(string Name, double Mass, long Distance, int NumberOfMoons);

internal static class PlanetData
{
public static Dictionary<string, Planet> PlanetInfo => new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0)},
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)},
{ "earth", new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)},
{ "mars", new Planet("Mars", 6.4171 * Math.Pow(10, 23), 235_610_000, 2)},
{ "jupiter", new Planet("Jupiter", 1.8982 * Math.Pow(10, 27), 743_830_000, 95)},
{ "saturn", new Planet("Saturn", 5.6834 * Math.Pow(10, 26), 1_458_000_000, 146)},
{ "uranus", new Planet("Uranus", 8.6810 * Math.Pow(10, 25), 2_934_600_000, 27)},
{ "neptune", new Planet("Neptune", 1.0241 * Math.Pow(10, 26), 4_472_700_000, 14)},
};
}
public record Planet(string Name, double Mass, long Distance, int NumberOfMoons);

internal static class PlanetData
{
public static Dictionary<string, Planet> PlanetInfo => new Dictionary<string, Planet>
{
{ "mercury", new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0)},
{ "venus", new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0)},
{ "earth", new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)},
{ "mars", new Planet("Mars", 6.4171 * Math.Pow(10, 23), 235_610_000, 2)},
{ "jupiter", new Planet("Jupiter", 1.8982 * Math.Pow(10, 27), 743_830_000, 95)},
{ "saturn", new Planet("Saturn", 5.6834 * Math.Pow(10, 26), 1_458_000_000, 146)},
{ "uranus", new Planet("Uranus", 8.6810 * Math.Pow(10, 25), 2_934_600_000, 27)},
{ "neptune", new Planet("Neptune", 1.0241 * Math.Pow(10, 26), 4_472_700_000, 14)},
};
}
Something like that Inconsistent accessibility is because your Planet record is private. Make it public or internal Basically you can't return a private class from a public member
sebt
sebtOPā€¢14mo ago
ahh i gotcha and it references planet ofc so it had to also be public
mtreit
mtreitā€¢14mo ago
Yeah
Angius
Angiusā€¢14mo ago
Also, protip, dictionary has an alternative syntax you might find cleaner:
new Dictionary<string, Planet>
{
["mercury"] = new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0),
["venus"] = new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0),
["earth"] = new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)
// ...
};
new Dictionary<string, Planet>
{
["mercury"] = new Planet("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0),
["venus"] = new Planet("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0),
["earth"] = new Planet("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)
// ...
};
And/or you can use a target-type new to not have to repeat new Planet everywhere
new Dictionary<string, Planet>
{
["mercury"] = new("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0),
["venus"] = new("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0),
["earth"] = new("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)
// ...
};
new Dictionary<string, Planet>
{
["mercury"] = new("Mercury", 3.3011 * Math.Pow(10, 23), 67_310_000, 0),
["venus"] = new("Venus", 4.8675 * Math.Pow(10, 24), 107_770_000, 0),
["earth"] = new("Earth", 5.972 * Math.Pow(10, 24), 148_720_000, 1)
// ...
};
sebt
sebtOPā€¢14mo ago
hmm ok i see and when i print a line from dictionary is there a way to get rid of the curly braces and make it a bit neater to the user i suppose
mtreit
mtreitā€¢14mo ago
I would probably rename the dictionary to just Planets, so you do PlanetData.Planets, a bit less redundant. So, that's what using record does, it implements ToString for you. If you want a different string representation, you can override ToString yourself.
Angius
Angiusā€¢14mo ago
Or manually interpolate the properties of the record
sebt
sebtOPā€¢14mo ago
so how do i put the record into action right now im just doing console.writeline(PlanetData.PlanetInfo["mercury"]);
Angius
Angiusā€¢14mo ago
$"Planet {planet.Name} has radius of {planet.Radius} and {planet.Moons} moons."
$"Planet {planet.Name} has radius of {planet.Radius} and {planet.Moons} moons."
With a var planet = PlanetData.PlanetInfo["mercury"] beforehand
mtreit
mtreitā€¢14mo ago
public record Planet(string Name, double Mass, long Distance, int NumberOfMoons)
{
public override string ToString()
{
// Change this to whatever you like...
return $"Name: {Name}, Mass: {Mass}, Distance: {Distance}, Number of moons: {NumberOfMoons}";
}
}
public record Planet(string Name, double Mass, long Distance, int NumberOfMoons)
{
public override string ToString()
{
// Change this to whatever you like...
return $"Name: {Name}, Mass: {Mass}, Distance: {Distance}, Number of moons: {NumberOfMoons}";
}
}
Example of overriding ToString
Angius
Angiusā€¢14mo ago
Or like that, yeah
sebt
sebtOPā€¢14mo ago
ahh nice man im learning so much thanks u guys so once i have overriden it does that mean whenever i output something from that dictionary with a name mass distance and no.moons the code knows to output it exactly as i have told it do
MODiX
MODiXā€¢14mo ago
Angius
REPL Result: Success
record Foo() {
public override string ToString() => "Oogabooga!";
}

var f = new Foo();
Console.WriteLine(f);
record Foo() {
public override string ToString() => "Oogabooga!";
}

var f = new Foo();
Console.WriteLine(f);
Console Output
Oogabooga!
Oogabooga!
Compile: 697.149ms | Execution: 72.227ms | React with āŒ to remove this embed.
sebt
sebtOPā€¢14mo ago
whats the deal with the variable f
Angius
Angiusā€¢14mo ago
It's just a variable
sebt
sebtOPā€¢14mo ago
yeah but why put it into a variable then output that
Angius
Angiusā€¢14mo ago
I mean, sure, I can just not
MODiX
MODiXā€¢14mo ago
Angius
REPL Result: Success
record Foo() {
public override string ToString() => "Oogabooga!";
}

Console.WriteLine(new Foo());
record Foo() {
public override string ToString() => "Oogabooga!";
}

Console.WriteLine(new Foo());
Console Output
Oogabooga!
Oogabooga!
Compile: 677.522ms | Execution: 110.834ms | React with āŒ to remove this embed.
Angius
Angiusā€¢14mo ago
That also works
sebt
sebtOPā€¢14mo ago
yeah i dont see the point of making a new variable when u can just output it directly and its the desired outcome but i suppose it can be easier to read
mtreit
mtreitā€¢14mo ago
It often helps with debugging
sebt
sebtOPā€¢14mo ago
yeah this is weird tho to me because i dont even mention the record but when i do Console.WriteLine(PlanetData.PlanetInfo["mercury"]); it is in the layout that is specified in the record automatically
Angius
Angiusā€¢14mo ago
The one specified in ToString() override? Well, yeah PlanetInfo is a dictionary of <string, Planet> When you get an item out of it, that item will be of type Planet
sebt
sebtOPā€¢14mo ago
ahh i see
Angius
Angiusā€¢14mo ago
Planet has a ToString() override And it will be used to... convert it to a string
sebt
sebtOPā€¢14mo ago
so if i put the method outside of the planet record then it wouldnt automatically convert it right?
Angius
Angiusā€¢14mo ago
Correct
sebt
sebtOPā€¢14mo ago
ok cool
Angius
Angiusā€¢14mo ago
See that override?
sebt
sebtOPā€¢14mo ago
ya
Angius
Angiusā€¢14mo ago
The base object class has a ToString() method already And record overrides that And you override... that
mtreit
mtreitā€¢14mo ago
Console.WriteLine calls ToString() on what you pass to it, to get what to print.
Angius
Angiusā€¢14mo ago
So if you were to override the ToString method of another class, it would only work for that class
sebt
sebtOPā€¢14mo ago
yeah so its about the placement and what is actually being affected by the override
Angius
Angiusā€¢14mo ago
It's about classes having methods And records having methods And structs having methods... It's how OOP works
sebt
sebtOPā€¢14mo ago
yeah well thanks guys its almost 3am for me so im gonna stop coding now but i appreciate the help i have learnt a lot
Accord
Accordā€¢13mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server