Passing String Arrays to Functions? [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm not sure what I'm doing wrong. I'm trying to pass the array people to the function getInformation and have it so stuff (eventually it will ask for the names of people and their salaries but I can't seem to get the function to take the array as a parameter?
using System;
class SalesPeeps {
string[] people = new string[8];
double[] salaries = new double[8];
static void Main() {
getInformation(people);
}
static void getInformation(string[] arr) {
int i = 0;
do {
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}

1) string[] people = new string[8];
is a field - not local variable. so when you say people - you are actually mean this.people but in static method there is no this.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
2) getInformation method use arr array as a parameter but do not reference to it. You can use people and make it static this will also fix problem from point 1.
I think this can be corrected this way:
class SalesPeeps
{
static string[] people = new string[8];
static double[] salaries = new double[8];
static void Main()
{
getInformation();
}
static void getInformation()
{
int i = 0;
do
{
Console.WriteLine("Please input a the sales person's last name.");
i++;
} while (i < people.Length);
}
}

You cannot access non-static field people from static method Main. Change its declaration to:
static string[] people = new string[8];

Both of your variables are class members, which means they are the variables of the objects you can create from the class SalesPeeps.
Your method getInformation() is a static method and therefore only accepts static inputs.
A fix for this would be to make both of your variables static. Read more here.
Either way, you should be getting a error message from the compiler and this question should not be necessary as there are plenty of resources on this topic. Just check your compiler errors in your IDE and google them.

Related

I get an error when running this program in C#: no overload for method 'Movies' takes '0' arguments. I need a method that does it [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want a method that gets input from the user, loops through the input, sorts the words that the user entered, and prints them sorted. (by the way, the language is c#). When I run the program, I get an error:
no overload for method 'Movies' takes '0' arguments"
there is the Main method but I couldn't put that in the code because StackOverflow will give me an error. the main method calls the method written below like this: Movies();
note: I am young and new to programming.
I know that I could do it just using the main method but I wanted to see what happens if I did that.
using System;
favoriteMovies = new string[4];
Console.WriteLine("Enter four movies: ");
for (int i = 0; i < favoriteMovies.Length; i++)
{
favoriteMovies[i] = Console.ReadLine();
}
Console.WriteLine("Here are the movies sorted alphabetically: ");
Array.Sort(favoriteMovies);
for (int i = 0; i < favoriteMovies.Length; i++)
{
Console.WriteLine(favoriteMovies[i]);
}
return favoriteMovies;
}
Since you don't show us more of your code, it is hard to guess where the error is. But I guess you write public static string[] Movies(var argument) instead of public static string[] Movies()
Here is what it would need to look like:
using System;
namespace Program{
class Program{
public static void Main(string[] args){
Movies();
}
public static string[] Movies(){
var favoriteMovies = new string[4];
Console.WriteLine("Enter four movies: ");
for (int i = 0; i < favoriteMovies.Length; i++)
{
favoriteMovies[i] = Console.ReadLine();
}
Console.WriteLine("Here are the movies sorted alphabetically: ");
Array.Sort(favoriteMovies);
foreach (string i in favoriteMovies)
{
Console.WriteLine(i);
}
return favoriteMovies;
}
}
}
I hope this will help you!
If not, please clarify your question!

Initialize int variable to minus one in C# [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I've come across some code where the variables are initialized to minus one. That's in some old code, is there any reason behind that? Because as far as I know all value types are initialized to zero.
I've tested the code and it doesn't change anything to leave the int variable uninitialized or with minus one, the result is the same.
Would you enlighten me?
class Program
{
static void Main()
{
SampleDelegate del = new SampleDelegate(SampleMethodOne);
del += SampleMethodTwo;
int Number = -1; //or -> int Number;
int returnedValue = del(out Number);
Console.WriteLine("returnedValue = {0}", returnedValue);
Console.ReadLine();
}
public static int SampleMethodOne(out int Number)
{
return Number = 1;
}
public static int SampleMethodTwo(out int Number)
{
return Number = 3;
}
}
public delegate int SampleDelegate(out int Number);
/returns 2
TL;DR: it depends, maybe there is no answer
Possible answer:
Initializing variable is better. you never know how it can be used in some later functions where having an unexpected value may be dangerous (when the code is optimized, you cannot be sure of the default value if not initialized).
In some case, an int may be used for some compatibility reason in the API when you just need an uint. In such a case, initializing to a negative value may be an easy way to detect an unset/invalid value.
No real reason, just an habit from the developer. I agree with comments, ask him if possible

Creating objects from constructors with arrays [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I'm a newbie and I'm trying to Console.Write() arrays from a constructor in Main. I am also trying to override ToString() to Console.Write() an array of ints as a string, but haven't found a clue how to do it.
namespace Z1
{
class List
{
public List(int b)
{
int[] tabb = new int[b];
Random r1 = new Random();
for(int i=0;i<b;i++)
{
tabb [i] =r1.Next(0, 100);
}
}
public List()
{
Random r2 = new Random();
int rInt1=r2.Next(0,10);
int[] tabc = new int[rInt1];
Random r3 = new Random();
for(int i=0;i<rInt1;i++){
tabc [i] = r3.Next(0,100);
}
}
}
class Program
{
static void Main()
{
List l1 = new List(10);
List l2 = new List();
Console.WriteLine(l1.ToString());
Console.WriteLine(l2.ToString());
}
}
}
The first thing to change are the two arrays. They are local variables and when you exit from the constructor they are simply discarded and you cannot use them anymore. I think you want just one array that could be created with a size specified by your user or with a random size between 1 and 10.
Finally you can override of ToString() in the usual way and return a Join of the array
class List
{
static Random r1 = new Random();
private int[] tabb;
public List(int b)
{
tabb = new int[b];
for (int i = 0; i < b; i++)
tabb[i] = r1.Next(0, 100);
}
// This constructor calls the first one with a random number between 1 and 10
public List(): this(r1.Next(1,11))
{ }
public override string ToString()
{
return string.Join(",", tabb);
}
}
Now your Main method could get the expected result.
As a side note, I suppose that this is just a test program so there is not much concern, but in a real program I strongly suggest you to avoid creating class with names that clashes with the classes defined in the framework. It is better to avoid names likes List, Task, Queue etc...
You can't just print the array, you'll have to print each value separately. Try using this instead of just Console.WriteLine();. Also make sure at the top of your class you have using LINQ;
l1.ToList().ForEach(Console.WriteLine);
l2.ToList().ForEach(Console.WriteLine);

Is encapsulate a private field into a variable a good practice? C# [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
For example:
public class Test
{
private string _s;
public Test()
{
var s = "hello";
_s = s;
}
public void Foo()
{
var s = _s;
// Use s for some reason.
}
}
Should I use _s directly for my needs or store _s into another variable that point to it? What if there were a property instead of the private field?
First, "encapsulate" is not at all the word for what you're doing. You're talking about making a copy. In programming, to "encapsulate" means to hide the field and make everybody access it via code of some kind. In C# that almost always means a property (which is really just method calls disguised by syntactic sugar). In other languages it might be explicit get and set methods.
So. Should you make a copy?
Yes:
private int _from = 9;
public void f(int to)
{
for (int i = _from; i < to; ++i)
{
// stuff
}
}
No:
public f2()
{
Console.WriteLine("from is {0}", _from);
}
If you're going to be changing the value as you use it, but you don't want the private field to be changed, make a local copy and change that.
But beware: Value types such as int behave very, very differently than mutable reference types such as SqlConnection (see below).
If you won't be changing it, don't waste your time. In fact, if the field is a reference type and you create a local reference to it, somebody maintaining your code ages hence may mistake it for a local object and wrongly assume that changes to it won't have class-wide effects.
private SqlConnection _conn = null;
public MyClass()
{
_conn = new SqlConnection();
}
public void f3()
{
var c = _conn;
// 150 lines of stuff
// OK, I guess we're done with it now!
c.Dispose();
c = null;
// Now _conn is not null, yet the next call to f3() will find it unexpectedly
// in an invalid state. You really don't want that.
}
Where did you get this idea from?
I see no reason to proxy the private field with a local variable. Most of the time, that field will be of a reference type (i.e., more or less, a class), so using a local variable only means one more reference to that object.
It could actually be harmful (anyway, doing unintended things) if you did that with a value-type field (an int, for example). You would act on the local variable, which is fine as long as you read it; but on write the field would not be changed.

How to address 3 parameters in my method program? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to write a C# code for the problem written below, but whatever I do, I can't figure out how to solve the problem. I guess I can't understand why it should be done the way it is asked! Anyways, this is what I need to do: Start a new console application.
In the Main method, Create a string array of size 5, name the array
Profile. Ask the user to input their first name, But you must do
that by calling a method you will write called GetStringInput This
method should require 3 parameters.
The first is a string, which is the question to ask the user. (For this first usage, you might pass in a string that says "enter your first name")
The second parameter is the Profile array
The third parameter is an int, the index, meaning, in which location in the array the user's answer should be stored.
First question (First name).
Ask the user for their last name, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their age, again, by calling that same GetStringInput,
but passing in a different question (note that the age will be entered and stored as a string, and not converted to an int)
Ask the user for their favorite color, again, by calling that same GetStringInput, but passing in a different question.
Ask the user for their favorite sport, again, by calling that same GetStringInput, but passing in a different question.
Now call a new method called DisplayProfile. This method should require a string array as a parameter, and you will pass in the Profile array. Add a Console.ReadLine(); statement and your Main method is done.
Now implement the 2 methods that you have been calling, GetStringInput and DisplayProfile. The DisplayProfile method should pull the information out of the array, and write out the values in a reasonable way.
Something like, for example Your name is John Smith, you are 21 years old. Your favorite color is green and your favorite sport is tennis.
Now, I have written this code:
static void Main(string[] args)
{
string[] Profile = new string[5];
GetUserInput(Profile);
DisplayProfile(Profile);
}
private static void DisplayProfile(string[] Showrofile)
{
Console.WriteLine("Your name is {0} {1}, you are {2} years old.\nYour favorite color is {3} and your favorite sport is {4}.",
Showrofile[0], Showrofile[1], Showrofile[2], Showrofile[3], Showrofile[4]);
}
public static string [] GetUserInput(string[] Getprofile)
{
string[] Question = new string[5];
Question[0] = "Enter your First name:";
Question[1] = "Enter your Last name:";
Question[2] = "Enter your Age:";
Question[3] = "Enter your Favorite color:";
Question[4] = "Enter your Favorite sport:";
for (int i = 0; i < Question.Length; i++)
{
Console.WriteLine(Question[i]);
Getprofile[i] = Console.ReadLine();
}
return Getprofile;
}
}
}
I don't know what to do. I appreciate your help!
I have been watching the comments and the other people are right, you should read how to ask the question because it wasn't clear. It does seem some simple Google searches would have answered this question very easily but I will take pity on your hair pulling. Here is an example of what you are asking for.
Sometimes the best approach is to walk away and then come back calm because when you were asking the Gabe how to make a method with three parameters you pretty much answered your own question. See below and good luck, take it slow.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
profile = GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
//Here is where you put the parameters you told Gabe about.
private static string[] GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
return profile;
}
Edit:
Since you brought it up in the comments about the teacher saying GetUserInput doesn't need to return anything you can see how it works. It would look like this.
public static void Main()
{
const int TOTAL_QUESTIONS = 5;
string[] profile = new string[TOTAL_QUESTIONS];
string[] questions = new string[]
{
"Enter your First name:",
"Enter your Last name:",
"Enter your Age:",
"Enter your Favorite color:",
"Enter your Favorite sport:"
};
for (int i = 0; i < TOTAL_QUESTIONS; i++)
{
GetUserInput(questions[i], profile, i);
}
DisplayProfile(profile);
}
private static void DisplayProfile(string[] profile)
{
Console.WriteLine($"Your name is {profile[0]} {profile[1]}, you are {profile[2]} years old.\nYour favorite color is {profile[3]} and your favorite sport is {profile[4]}.");
}
private static void GetUserInput(string question, string[] profile, int index)
{
Console.WriteLine(question);
profile[index] = Console.ReadLine();
}

Categories