C
C#

help

❔ Adding to Arrays Via Methods

HHumNumWorld2/6/2023
I am having trouble getting arrays to be changed by methods. I tried lists as well. Please send help.
AAngius2/6/2023
You can't append items to arrays
They're fixed-size
Use a List<T>
HHumNumWorld2/6/2023
string[] plants = {};

createPlant(ref plants);
createPlant(ref plants);
createPlant(ref plants);
Console.WriteLine(plants[0] + plants[1]);
Console.ReadLine();
// avolva aventine  
static void createPlant(ref string[] plants)
{
    Console.WriteLine("What is the Name of your Plant?");
    plants = new string[] { Console.ReadLine() };
    Console.Write("Completed! Push any Button to Exit.");
    Console.ReadLine();
    //may just have to for now.
    string print = ""; 
    for (int i = 0; i < plants.Length; i++) 
    {
        Console.Write(plants[i] + ", ");
    }
    Console.WriteLine(print);
    Console.ReadLine();
}

@Angius thanks but look at this
HHumNumWorld2/6/2023
HHumNumWorld2/6/2023
its error after error
AAngius2/6/2023
The parameter is declared as a string[], so obviously it won't take a List<string>
Also, in your CreatePlant() method you crate a brand new array
You don't add anything, you replace
HHumNumWorld2/6/2023
can you explain that
AAngius2/6/2023
What's to explain there?
Square peg doesn't fit into a round hole
int and string are different types
So are boolean and UngaBunga
HHumNumWorld2/6/2023
where is the square peg
AAngius2/6/2023
So are string[] and List<string>
List<string> is the square peg
The method has a round hole, string[] type parameter
List<T> is not T[]
HHumNumWorld2/6/2023
oh ignore the writeline
AAngius2/6/2023
Nothing to do with any writeline
HHumNumWorld2/6/2023
HHumNumWorld2/6/2023
right here where is the []
HHumNumWorld2/6/2023
HHumNumWorld2/6/2023
and ignore line 27 for now
im just trying to get the errors off the first part until it functions
AAngius2/6/2023
Aight, so, why do you try to pass ref List<string> plants as a parameter?
Do you also use Console.WriteLine(string "message")?
HHumNumWorld2/6/2023
apparently to change a variable in a function you have to use ref
I tried just "plants" but it said it has to be written like a list
AAngius2/6/2023
Yeah, in the parameter declaration
HHumNumWorld2/6/2023
was there a better way of doing that
AAngius2/6/2023
When you call the method, you don't supply a type
You just pass the param
HHumNumWorld2/6/2023
wym
AAngius2/6/2023
CreatePlant(plants)
HHumNumWorld2/6/2023
oh
HHumNumWorld2/6/2023
HHumNumWorld2/6/2023
like this?
AAngius2/6/2023
Not here
Jesus
$helloworld
HHumNumWorld2/6/2023
im used to javascript
AAngius2/6/2023
You really should brush up the basics
HHumNumWorld2/6/2023
its much easier when I could do something like:

appendItem("plants", "");
which I dont even know if thats a real thing
AAngius2/6/2023
And you can
HHumNumWorld2/6/2023
because I learned from code.org
AAngius2/6/2023
var plants = new List<string>();
plants.Add("carrot");
plants.Add("hydrangea");
plants.Add("juniper");

List has the .Add() method
HHumNumWorld2/6/2023
yeah see I get that
but I called plants in main
and im trying to add in a method
and its causing tons of errors to get it through the parameters
like in js, everything is global pretty much
I just say:

var x = 1

function addOne() {
x ++;
}

and var becomes 2 if I call the function
in c# i'm just lost with methods and why they are so isolated
you have to use ref for some reason for it to change anything, and even still its like a maze to get the errors to be broken
AAngius2/6/2023
AAngius2/6/2023
For reference types, you don't need to use ref
HHumNumWorld2/6/2023
List<string> plants = new List<string>();
createPlant(ref List<string> plants);
Console.ReadLine();

static void createPlant(plants)
{
    Console.WriteLine("What is the Name of your Plant?");
    plants.Add(Console.ReadLine());
    Console.Write("Completed! Push any Button to Exit.");
    Console.ReadLine();
    //may just have to for now.
    string print = ""; 
    for (int i = 0; i < plants.Length; i++) 
    {
        Console.Write(plants[i] + ", ");
    }
    Console.WriteLine(print);
    Console.ReadLine();
}

oh let me read this rq
AAngius2/6/2023
And here's the fix to your issue
You declare types when declaring the method
There and only ever there
When calling that method, you don't declare any types
Just pass the params
HHumNumWorld2/6/2023
AAngius2/6/2023
Cool, what does the error say
HHumNumWorld2/6/2023
argument 1 must be passed with the 'ref' keyword
AAngius2/6/2023
Well, try that
HHumNumWorld2/6/2023
oh wow
ok brb
ok yeah its cleared up
next issue though
HHumNumWorld2/6/2023
AAngius2/6/2023
Again, what does the error say?
probably says that .Length property doesn't exist on List<T>
HHumNumWorld2/6/2023
AAngius2/6/2023
That's because those are the properties List<T> has: https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-7.0#properties
.Length is not among them
.Count, however, is
HHumNumWorld2/6/2023
are there any substitutes
ah
thats weird
i'll try it
oh wow thats wonderful
it works
ok now I need a few clarifications so I really grasp this
this is whats confusing me
its the whole parameters and redeclarations thing
AAngius2/6/2023
The method declares what it wants
void Foo(string x, int y) {}

like this one, that wants a string and an int
When calling that method, you don't need to say that you're passing a string
HHumNumWorld2/6/2023
hold up
AAngius2/6/2023
No need to do
string x = "hello";
Foo(string x, int 69);

because the method will not let you pass anything else. You just do
string x = "hello";
Foo(x, 69);
HHumNumWorld2/6/2023
wow
so ref only needs to be sent in the declaration of the method
AAngius2/6/2023
Admittedly, I haven't really worked with ref
HHumNumWorld2/6/2023
it seems so obvious, swapping syntaxes really gets me a headache
AAngius2/6/2023
To begin with, List<T> already is a reference type
HHumNumWorld2/6/2023
a what?
AAngius2/6/2023
You're already passing a reference to it, not a copy
$refvsvalue
AAngius2/6/2023
In C# there are value types — mostly the basic ones like int, bool, etc
And reference types — custom classes and stuff
Value types, when passed, create a copy
Reference types pass a reference
HHumNumWorld2/6/2023
oh
so I only use ref when I need to make the copy change something outside
AAngius2/6/2023
ref coerces value types to be passed as reference
HHumNumWorld2/6/2023
wait
so saying a variable prints it?
I see you wrote list
AAngius2/6/2023
That list without a semicolon is just something the repl of the bot does
HHumNumWorld2/6/2023
ah
I had trouble earlier with printing arrays
AAngius2/6/2023
Here's how ref works for value types
Without ref, the change happened inside of the method, the copy of the number was changed
With ref, the change happened inside and outside of the method
HHumNumWorld2/6/2023
Sorry my network is acting up. So I get it now! reference = ref. if I did val to a ref then would it act like a value?
AAngius2/6/2023
No
You can pass a value type as a reference, but you can't turn a reference type into a value type
HHumNumWorld2/6/2023
hm
and I know this is off topic
but what do you do for the " cannot implicitly convert type 'string' to 'int' " error
AAngius2/6/2023
int.Parse() for example
Or better yet, int.TryParse()
But this one's a little more complex
HHumNumWorld2/6/2023
what
what do those mean
HHumNumWorld2/6/2023
what does the word parse mean
AAngius2/6/2023
It's the name of the method...?
Like Console.WriteLine()
HHumNumWorld2/6/2023
I'm guessing over all it converts
AAngius2/6/2023
It parses a string into a number, yeah
You could say converts, sure
HHumNumWorld2/6/2023
and one last question
how do you close the program through code
AAngius2/6/2023
Once it completes, it'll just close
IIRC you can just return from it as well
HHumNumWorld2/6/2023
ah ty
thats everything, thank you for your help!
AAngius2/6/2023
Anytime
AAccord2/7/2023
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.

Looking for more? Join the community!

Recommended Posts
❔ Issue: Retrieving Encrypted User Entry from MS SQL ServerHi Folks, thanks for you Time in Advance, Description: I am working on a .Net MAUI application usi❔ Windows Forms ProjectI am close to giving up but I need this class to graduate... I have ruined my progress so I am start❔ Something is wrong here but idk (UNITY)So I am following a tutorial but apparently there is something wrong in this code and I don't know w❔ ✅ Semi-Random-GeneratorSo I'm trying to generate a list for scheduling people to a task. What I intend is to generate the l✅ Collection appears to be null, even though it's not null on DBI think the pictures already show the problem in more detail, there isn't much to it. User and Pers❔ Using C# and SQLite, I'm inputting a formatted date, and it's writing tot the database as a sumA strange one, to be sure. I'm inputting something like '2022-01-13', and it's writing '2008'. Wou❔ What is the difference between string pool and intern pool?In the Windows Community Toolkit's high performance library, there is a string pool. What makes this✅ Exception is caught, but not?I have this piece of code ``` try { await _dbContext.RunningTotals.AddA❔ For loops, for this project.This Project needs me to create a table with a loop of data for the input altitude. Where I'm havingvoid and returnFor starters I still don't undersatnd basically everything so sorry for being stupid Do you always h❔ Handling of objects which correspond to a given rule by editing again.**The situation:** The user can create objects in a list via the UI. If there are already one or mor✅ Set up SpecFlow Logging with 2 different projectsCurrently I am trying to do some logging while using the SpecFlow BDD framework. In my solutions I h❔ ✅ AddSingleton and AddDbConnection are not running whatsoeverI have this code ```cs services.AddSingleton<DbConnection>(_ => { SqliteConnectionStringBuilder ❔ cast parent to childHave a problem about inheritance. I have an interface that are shared between a net framework projec❔ Warn on VS consolehey, ik I'm new here but yesterday i was setting up VS Code for unity, i got the .net SDK and the C#❔ VB.NetHello I use VB.Net but need help but no one uses it. Is C# similar and can you guys help me❔ Help with linq queryI have a list of cutomers that gets grouped according to their addresss and data property. I would l❔ Help in questionHello I need help solving a question that says: i need to write a program that receives 4 points lik❔ Unity Asset Bundle ErrorWhen using my script I keep getting this error: ``tmp\PREFABROOT\Mesh\Body(Clone).mesh" has been a❔ Moving from Development to ProductionI want to be more secure in my .NET server application, atm my db connection string is just stored i