Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
RockiLocky

Methods able to return Arrays?

Got it working :D

Glad that you sorted it out :)

One more question I have is why does the Array need to be static?

It has to be static because you are accessing it from static contexts.

Does static not mean that nothing outside of this class has no rights to change something on it or did I missunderstood something.

No it means quite the opposite - see static and Access Modifiers.

And must it be a Array because everything else is static???

I'm not sure what it is that you are asking here...

Sorry I have been quite brief, usually I expand a little more but I'm about to go to bed :)

Because you have that array declared at class scope you don't need to pass it into the method in order to access it (just get rid of that first parameter altogether).

Recommended Posts

Posted · Original PosterOP

Hi guys,

 

 

So right now I am making some small projects just to get more and mroe familiar with the speech C#, right now I am programming a Random Group Generator. So, because I just started the ammount of Code is not there really, if you think I can do something better coding wise and Interface I would apreciate the help and also would like to implement, but because this is just a start I am going to keep it simple to get the function going.

 

 

So now to my problem, to explain this I will post the code so you have easier time to understand what I am doing:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Random_Group_generator_Konsolenanwendung{    class Program    {        public         static void Main(string[] args)        {            int AmmountofPeopleHighestGroup;            Console.WriteLine("Welcome to the Random Group Generator!");            Console.Write("Up to how many members should there be in the highest group: ");            AmmountofPeopleHighestGroup = int.Parse(Console.ReadLine());            Console.WriteLine(" ");            MemberofGroup(AmmountofPeopleHighestGroup);            Console.WriteLine("Here is the test if it worked: ");            Console.ReadKey();        }        static void MemberofGroup(int AmmountofGroups)        {            int[] A = new int[AmmountofGroups + 1];             //For Loop to let the User type in how many Groups of wich he has.            for (int i = 1; i <= AmmountofGroups; i++)            {                Console.Write("How many Groups of " +i +" do you want: ");                A[i] = int.Parse(Console.ReadLine());            }        }    }}

So in the Method MemberofGroup I want to return the Array, so I can use this for another Method what is going to follow. Just for testing porpuse I wanted to just write it out so I can see that it is working and I can give it over to another function, but this writing out will be removed after it worked.

 

What I wanted to try is to create an Array with a Name in the void Main and then just make a out parameter in the Method(I know it is void and it can't give something back, that was because I thought I would not need anything from in there actually) and give it over to the Main variable then.

 

 

 

One other question is what is a good way to declare variables, because I am new I am not really sure how to call them. I hear it is usefull to call them what they are doing or what they are related to. But yeah.

 

 

 

Hope you guys can help me out

Link to post
Share on other sites
From what I understand, you want to declare an array inside the main method, pass it onto your MemberOfGroup method, and have these results reflect back into main method after the call?
 
You have two options, and the one you should use depends on what exactly you want to do (I'm afraid I didn't quite understand what you're currently doing). 
One is to create an instance variable for the class. This means declaring these variables outside of the methods. 
The second option is to receive the array as a parameter in the MemberOfGroup method. In C#, when you pass a "reference type" parameter to a method, you get a copy of its reference, so changes to that reference actually reflect on the original variable.
 
What I mean is:
using System.IO;using System; class Program{    static void Main()    {        int [] s = new int[1];        s[0] = 0;        test(s);        Console.WriteLine(s[0]);    }         static void test(int [] sr){        sr[0] = 1;    }}

Will output 1, not 0.


Want to solve problems? Check this out.

Link to post
Share on other sites
Posted · Original PosterOP

 

From what I understand, you want to declare an array inside the main method, pass it onto your MemberOfGroup method, and have these results reflect back into main method after the call?
 
You have two options, and the one you should use depends on what exactly you want to do (I'm afraid I didn't quite understand what you're currently doing). 
One is to create an instance variable for the class. This means declaring these variables outside of the methods. 
The second option is to receive the array as a parameter in the MemberOfGroup method. In C#, when you pass a "reference type" parameter to a method, you get a copy of its reference, so changes to that reference actually reflect on the original variable.
 
What I mean is:
using System.IO;using System; class Program{    static void Main()    {        int [] s = new int[1];        s[0] = 0;        test(s);        Console.WriteLine(s[0]);    }         static void test(int [] sr){        sr[0] = 1;    }}

Will output 1, not 0.

 

No what I want to do is I can declear a public array and that one is going the initialized in the MemberOfGroup Method and then send to the main method thats the problem I have

 

 

K sry I read through your text a 2nd time, saw the reference with ref am I also able to give over the Array right and as soon as I call the method and it is finished the public Array will be updated right?

Link to post
Share on other sites

If you pass a reference type (such as an array, an object, etc) by value (like in my example), a reference to that "variable" is passed to the method. This means that if you change that variable inside the method, the changes you make will still be there when it returns back to the main method. So, yes, it will be updated.


Want to solve problems? Check this out.

Link to post
Share on other sites
Posted · Original PosterOP

If you pass a reference type (such as an array, an object, etc) by value (like in my example), a reference to that "variable" is passed to the method. This means that if you change that variable inside the method, the changes you make will still be there when it returns back to the main method. So, yes, it will be updated.

One question I have is in this code:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Random_Group_generator_Konsolenanwendung{    class Program    {        public int[] B = new int[1];        static void Main(string[] args)        {            int AmmountofPeopleHighestGroup;            Console.WriteLine("Welcome to the Random Group Generator!");            Console.Write("Up to how many members should there be in the highest group: ");            AmmountofPeopleHighestGroup = int.Parse(Console.ReadLine());            Console.WriteLine(" ");            MemberofGroup(ref B, AmmountofPeopleHighestGroup);  //How do I give over the Array to the Method??        }        static void MemberofGroup(ref int[] B, int AmmountofGroups)        {            int[] A = new int[AmmountofGroups];             //For Loop to let the User type in how many Groups of wich he has.            for (int i = 0; i <= (AmmountofGroups - 1); i++)            {                Console.Write("How many Groups of " +(i+1) +" do you want: ");                A[i] = int.Parse(Console.ReadLine());            }        }    }}

If you look at the code and at the top I have made a public Array so every Method can use it, then when I wanted to give over the Array it didn't work so my question now is how do I give it over?

Also before I give it over it should not already know how big it is, thats gonna happen in the Method down below. And from the Code from above you gave me you already knew how big the Array is gonna be tahts not what I want to. Thats why I first want to create it in the Method MemberofGroups (the Array) and then just return it to the void Main so I can then give it over to a new method.

 

 

 

 

 

And to let you know what I am doing is:

 

I am making a programm wich creates groups out of people randomly, so lets say you got 4 people: Guy A, Guy B, Guy C and Guy D, now you want to make 2 groups of 2 and instead of you choosing wich guys get togheter my programm will do that for you so it will create the groups randomly, so lets say for example 1.) Group: Guy A and Guy C  and in 2.) Group: Guy B and Guy D, so it also only puts each person only once in a group and not in multiple.

 

 

And thats basicly what I am going to code myself and now I need that arrow from above so I know how many groups of 2 I have and how many of 3 and so on.  BTW just to let you know there will be a method where the guy types in the names of the persons so yeah.

 

 

 

 

Hope you can help me out now abit better.

Link to post
Share on other sites

I'm having a really hard time following what exactly it is that you are attempting to accomplish here. In any event if you have a method that is only responsible for the initialization of something (which it seems to be what you have going on here) then it would be more correct if you encapsulated that behaviour and passed the product out.

        private static int[] InitializeArray(int someSize)        {            // Whatever other initialization code...            return new int[someSize];        }

The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
Posted · Original PosterOP

 

I'm having a really hard time following what exactly it is that you are attempting to accomplish here. In any event if you have a method that is only responsible for the initialization of something (which it seems to be what you have going on here) then it would be more correct if you encapsulated that behaviour and passed the product out.

        private static int[] InitializeArray(int someSize)        {            // Whatever other initialization code...            return new int[someSize];        }

I hope I can clarify that much better now.

 

 

 

Idea:  My Idea is to make a programm that is able to make the members of groups randomly. Meaning if you got 1 group of 2 and 3 gourps of 3 then it would look like that:

Names first ofc:  Guy A, Guy B, Guy C, Guy D, Guy E, Guy F, Guy G, Guy H, Guy I, Guy J, Guy K

Group of 2: Guy H(randomly choosen)   and Guy B(randomly choosen)  

Group of 3:Guy A(randomly choosen), Guy G(randomly choosen)  and Guy I(randomly choosen)  

Group of 3:Guy B(randomly choosen), Guy D(randomly choosen)  and Guy F(randomly choosen)  

Group of 3:Guy C(randomly choosen), Guy J(randomly choosen)  and Guy E(randomly choosen)

 

 

So depending on how many groups you have and how many members there are per group it will randomly generate these group members and everyone will only be once, because there cannot be one guy in 2 groups.

One thing that could be important to know to is: I am trying to do as much as possible with methods so my void Main is not having all the code in it.

 

Now to the problem:

 

Before adressing the problem straight will give you more info so you understand everything!

My problem is as you see I need a Array that can store the numbers of groups somebody wants, to the example of abouth the wants 1 group of 2 and 3 group of 3, So my Array should look like this:

 

A[0] = 0;   //Groups of 0

A[1] = 0;   // Groups of 1

A[2] = 1   // Groups of 2

A[3] = 3;  //Groups of 3

//Not the exact as the code, because I didn't wan the A[0] to be empty always so I set everything 1 down so I start basicly from 3 meaning A[1] is Groups of 2 and A[2] is Groups of 3 and so on

 

 

Now to the variable AmmountofGroups I am using in the for loop and to the AmmountofPeopleHighestGroup I give over to the Method what is basiclyAmmountofGroups, that means    AmmountofPeopleHighestGroup = AmmountofGroups;

To clarify that abit better I will use the example of above.

 

 

So the Console Will type that out:

Welcome to the Random Group Generator!

Up to how many members should there be in the highest group: 3(what you type in)         //In this moment you write how many persons are in the highest group you have, so in our example 3 because our highest group contains 3 people

 

 

//Now my Console will write this out:

How many Groups of 2 do you want: 1(what you type in)                                              //In this moment it will ask you how many groups do you have wich contain 2 people, so in our example we only have 1 group that contains 2 people

How many Groups of 3 do you want: 3(what you type in)                                              //In this moment it will ask you how many groups do you have wich contain 3 people, so in our example we have 3 groups that contain 3 people

 

 

//Thats what I have till yet the rest will follow. So now to say it, You before typed in the Highest group you have contains 3 people so the programm ofc will not ask you "How many Groups of 4 do you want: ", because you typed in 3 before.

 

 

 

After I said that I will let you know what I want to do.

 

As you can see is I am creating a Array wich contains x variables depending on wich number you have as input. After that it will give you the output as stated before where it asks you "How many Groups of x do you want: ", after this is done this whole Array, wich how big it is depends on the input of the user, should be send to the void main or somewhere, because this Array I will need to use in another Method that will come up, so basicly after this method is done, my void Main will open a new Method where to input parameter will be this array.

 

 

So my problem now is I want to give this Array back to main with return or something and then use it as an input, but I have no clue how to do that I only know it with variables not with Arrays.

 

 

 

 

 

Hope this helped you if you have more questions let me know pls appreciate your help

Link to post
Share on other sites

So my problem now is I want to give this Array back to main with return or something and then use it as an input, but I have no clue how to do that I only know it with variables not with Arrays.

 

Well I think this is an interesting line. Are you sure that you understand how reference and value types work in C#?

 

Let's take this Array as a quick example. When you instantiate an array i.e. int[] you are instantiating a type that derives from System.Array thus your variable (the handle that you use to get at your new array) is actually storing a reference to the array and not the array itself. The array is allocated on the managed heap.


The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
Posted · Original PosterOP

Well I think this is an interesting line. Are you sure that you understand how reference and value types work in C#?

 

Let's take this Array as a quick example. When you instantiate an array i.e. int[] you are instantiating a type that derives from System.Array thus your variable (the handle that you use to get at your new array) is actually storing a reference to the array and not the array itself. The array is allocated on the managed heap.

Yes I do how ref and such works, I know if you give reference over it will overwrite your normal value, the problem is my Array is depending on the Users input so I cannot declear or initialize it globaly (public), because I do not know yet how bit it is gonna be.

 

I also understand with the heap but as said I do not know how big it is and for reasons to not make the programm bigger also if it is only Bytes we are talking here it is always good to save there and here.

 

 

So I am trying to do that :D

Link to post
Share on other sites

Yes I do how ref and such works, I know if you give reference over it will overwrite your normal value, the problem is my Array is depending on the Users input so I cannot declear or initialize it globaly (public), because I do not know yet how bit it is gonna be.

 

That's great but I'm not referring to the ref keyword. I hope that you realise this so that we are clear. Also the public keyword does not denote global access... 

 

 

I also understand with the heap but as said I do not know how big it is and for reasons to not make the programm bigger also if it is only Bytes we are talking here it is always good to save there and here.

 

 

So I am trying to do that  :D

 

I don't know about anyone else but I really can't understand that sorry xD


The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
Posted · Original PosterOP

That's great but I'm not referring to the ref keyword. I hope that you realise this so that we are clear. Also the public keyword does not denote global access... 

 

 

 

I don't know about anyone else but I really can't understand that sorry xD

K got that you are not referring to the keyword ref.

 

 

 

As said before I am just trying to make an array wich I can work with in the whole class. And the only thing that needs to be set is that it is not declared how long the array is that will happen in the method so if you can help me out with that,that would be awesome, thats basicly the whole problem that I need to use an array in the whole class and it is not defined from the start on how long it is.

 

Hope that helps you :D

Link to post
Share on other sites

K got that you are not referring to the keyword ref.

 

 

 

As said before I am just trying to make an array wich I can work with in the whole class. And the only thing that needs to be set is that it is not declared how long the array is that will happen in the method so if you can help me out with that,that would be awesome, thats basicly the whole problem that I need to use an array in the whole class and it is not defined from the start on how long it is.

 

Hope that helps you :D

 

Yes of course. Why can't you simply declare the array and then instantiate it based on user input at runtime? Either still have the array declared at the class level (with the instantiation occurring at runtime) and access it in each method - you won't have to pass it about at all or just pass it between methods like many of the examples you have already been provided with.


The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
Posted · Original PosterOP

Yes of course. Why can't you simply declare the array and then instantiate it based on user input at runtime? Either still have the array declared at the class level (with the instantiation occurring at runtime) and access it in each method - you won't have to pass it about at all or just pass it between methods like many of the examples you have already been provided with.

K thx will do that then.

 

 

So jsut to be sure what you are saying.

 

I should make an Instantiation for the Array and then just give the Array over to the methods where I need it. If you mean taht how do I write the Array correctly in the parameters of a Method and when I call it up thats kindaly the problem I have too I do not know how to write so I can give over an Array to a method.

 

 

And sry for all them questions and you being patient

Link to post
Share on other sites
Posted · Original PosterOP

Yes of course. Why can't you simply declare the array and then instantiate it based on user input at runtime? Either still have the array declared at the class level (with the instantiation occurring at runtime) and access it in each method - you won't have to pass it about at all or just pass it between methods like many of the examples you have already been provided with.

 

 

Got it working :D

 

 

Here is the code will comment out what I changed so yeah :D

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Random_Group_generator_Konsolenanwendung{    class Program    {        static int[] Groups;                                                               //created a static Array wich is not initialized yet        static void Main(string[] args)        {            int AmmountofPeopleHighestGroup;            Console.WriteLine("Welcome to the Random Group Generator!");            Console.Write("Up to how many members should there be in the highest group: ");            AmmountofPeopleHighestGroup = int.Parse(Console.ReadLine());            Console.WriteLine(" ");            MemberofGroup(ref Groups, AmmountofPeopleHighestGroup);                        //able to write in the Array correctly             Console.WriteLine("Here is the test if it worked: " + Groups[1]);            Console.ReadKey();        }        static void MemberofGroup(ref int[] Group, int AmmountofGroups)                    //was able after  long time to take a Array to this method        {            Groups = new int[AmmountofGroups];            //For Loop to let the User type in how many Groups of wich he has.            for (int i = 0; i <= (AmmountofGroups - 1); i++)            {                Console.Write("How many Groups of " +(i+1) +" do you want: ");                Groups[i] = int.Parse(Console.ReadLine());            }        }    }}

One more question I have is why does the Array need to be static?

 

Does static not mean that nothing outside of this class has no rights to change something on it or did I missunderstood something.

 

And must it be a Array because everything else is static???

 

 

 

Thx if you can help me with my last question :D

Link to post
Share on other sites
Posted · Best Answer

Got it working :D

Glad that you sorted it out :)

One more question I have is why does the Array need to be static?

It has to be static because you are accessing it from static contexts.

Does static not mean that nothing outside of this class has no rights to change something on it or did I missunderstood something.

No it means quite the opposite - see static and Access Modifiers.

And must it be a Array because everything else is static???

I'm not sure what it is that you are asking here...

Sorry I have been quite brief, usually I expand a little more but I'm about to go to bed :)

Because you have that array declared at class scope you don't need to pass it into the method in order to access it (just get rid of that first parameter altogether).


The single biggest problem in communication is the illusion that it has taken place.

Link to post
Share on other sites
using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1{    class Program    {        static IList<Person> _people;        static IList<Group> _groups = new List<Group>();        static Random _rand = new Random();        static void Main(string[] args)        {            var numPeople = ReadInt("Enter amount of people: ");            _people = GeneratePeople(numPeople);            var maxPeople = ReadInt("Enter amount people in the group with most members: ");            for (var i = 1; i <= maxPeople; i++) // does not make sense to make groups of 0 members...            {                var numGroups = ReadInt("How many groups of " + i + " people do you want? ");                for (var j = 0; j < numGroups; j++)                    _groups.Add(new Group { Size = i, Name = "G" + i + j });            }            foreach (var g in _groups)            {                do                {                    // pick random person                    var person = _people[_rand.Next(_people.Count)];                    _people.Remove(person);                    g.Members.Add(person);                } while (!g.IsFull);            }            Console.WriteLine("Generated following groups:");            foreach (var g in _groups)                Console.WriteLine(g.ToString());            Console.ReadLine();        }        static int ReadInt(string message)        {            var ok = false;            int val = 0;            while (!ok)            {                try                {                    Console.WriteLine(message);                    var input = Console.ReadLine();                    val = Int32.Parse(input);                    ok = true;                }                catch                {                    Console.WriteLine("Please enter a numeric value");                }            }            return val;        }        static IList<Person> GeneratePeople(int number)        {            var people = new List<Person>(number);            for (var i = 0; i < number; i++)                people.Add(new Person { Name = "Guy" + i });            return people;        }    }    public class Person    {        public string Name { get; set; }    }    public class Group    {        public string Name { get; set; }        public List<Person> Members { get; set; }        public int Size { get; set; }        public bool IsFull        {            get { return Members.Count == Size; }        }        public Group()        {            Members = new List<Person>();        }        public override string ToString()        {            var sb = new StringBuilder();            sb.AppendLine(Name);            foreach (var member in Members)                sb.AppendLine("\t" + member.Name);            return sb.ToString();        }    }}

Some OOP sprinkled on top. Notice how I am not doing anything strange using ref or similar to manage the groups. I just generate them once and modify the objects.

Link to post
Share on other sites
Posted · Original PosterOP

Glad that you sorted it out :)

It has to be static because you are accessing it from static contexts.

No it means quite the opposite - see static and Access Modifiers.

I'm not sure what it is that you are asking here...

Sorry I have been quite brief, usually I expand a little more but I'm about to go to bed :)

Because you have that array declared at class scope you don't need to pass it into the method in order to access it (just get rid of that first parameter altogether).

Hey just wanted to thank you for all your help i hope you wont bother if I got once a question again and would ask you :D

Link to post
Share on other sites
Posted · Original PosterOP
using System;using System.Collections.Generic;using System.Text;namespace ConsoleApplication1{    class Program    {        static IList<Person> _people;        static IList<Group> _groups = new List<Group>();        static Random _rand = new Random();        static void Main(string[] args)        {            var numPeople = ReadInt("Enter amount of people: ");            _people = GeneratePeople(numPeople);            var maxPeople = ReadInt("Enter amount people in the group with most members: ");            for (var i = 1; i <= maxPeople; i++) // does not make sense to make groups of 0 members...            {                var numGroups = ReadInt("How many groups of " + i + " people do you want? ");                for (var j = 0; j < numGroups; j++)                    _groups.Add(new Group { Size = i, Name = "G" + i + j });            }            foreach (var g in _groups)            {                do                {                    // pick random person                    var person = _people[_rand.Next(_people.Count)];                    _people.Remove(person);                    g.Members.Add(person);                } while (!g.IsFull);            }            Console.WriteLine("Generated following groups:");            foreach (var g in _groups)                Console.WriteLine(g.ToString());            Console.ReadLine();        }        static int ReadInt(string message)        {            var ok = false;            int val = 0;            while (!ok)            {                try                {                    Console.WriteLine(message);                    var input = Console.ReadLine();                    val = Int32.Parse(input);                    ok = true;                }                catch                {                    Console.WriteLine("Please enter a numeric value");                }            }            return val;        }        static IList<Person> GeneratePeople(int number)        {            var people = new List<Person>(number);            for (var i = 0; i < number; i++)                people.Add(new Person { Name = "Guy" + i });            return people;        }    }    public class Person    {        public string Name { get; set; }    }    public class Group    {        public string Name { get; set; }        public List<Person> Members { get; set; }        public int Size { get; set; }        public bool IsFull        {            get { return Members.Count == Size; }        }        public Group()        {            Members = new List<Person>();        }        public override string ToString()        {            var sb = new StringBuilder();            sb.AppendLine(Name);            foreach (var member in Members)                sb.AppendLine("\t" + member.Name);            return sb.ToString();        }    }}

Some OOP sprinkled on top. Notice how I am not doing anything strange using ref or similar to manage the groups. I just generate them once and modify the objects.

 

Saw that thx. Using it right now :D

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


×