0

Since I'm a total beginner I don't know much about C# yet.
I want to use the returned string from Method 1 in my main method.
Shouldn't I be able to use it since Method1 is public?

public string Method1() { Console.Write("Vorname: "); string vorname = Convert.ToString(Console.ReadLine()); Console.Write("Nachname: "); string nachname = Convert.ToString(Console.ReadLine()); Console.Write("Adresse: "); string adresse = Convert.ToString(Console.ReadLine()); string info = vorname + nachname + adresse; return (info); } static void Main(string[] args) { string dateipfad = @"C:\Users\kaihe\Documents\persönliche_informationen.txt"; AllMethods txtfileabfrage = new AllMethods(); txtfileabfrage.Method2(); AllMethods input = new AllMethods(); Console.WriteLine(info); File.WriteAllText(dateipfad, info); Console.ReadKey(); } 
3
  • 1
    What is the class name that contains this code? Commented Mar 13, 2017 at 16:36
  • 2
    Method1 needs to be static if you want to call it from a static method. And the Convert.ToString is unnecessary because Console.ReadLine returns a string already. Commented Mar 13, 2017 at 16:38
  • Where are you trying to call Method1()? Commented Mar 13, 2017 at 16:41

2 Answers 2

3

Method1 should also be static since you are calling from Main which is static.

Sign up to request clarification or add additional context in comments.

Comments

0

If you add the static keyword to Method1() you will be able to call Method1() from the main method.

 static void Main(string[] args) { String returnedValue = Method1(); } public static string Method1() { Console.Write("Vorname: "); string vorname = Convert.ToString(Console.ReadLine()); Console.Write("Nachname: "); string nachname = Convert.ToString(Console.ReadLine()); Console.Write("Adresse: "); string adresse = Convert.ToString(Console.ReadLine()); string info = vorname + nachname + adresse; return (info); } 

4 Comments

You need to save the returned value to a variable otherwise it cannot be used.
Well actually there is no need to store the returned value. You could use it like so: Console.WriteLine(Method1());
If you look at OP's original code - you will see that "info" (presumably the expected returned value) is used twice - so storing in a variable IS required (calling method1 twice would result in requiring the data to be input twice).
Yes I agree that OP wants to store the output of his method however it is still untrue that "You need to save the returned value to a variable otherwise it cannot be used".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.