Max Goddard Max Goddard - 1 year ago 234
C# Question

C# Parameters for Returning a Private Variable From a Public Method

Whereas in VB standard programming practice with classes is to set a private variable directly and only access it through a public method to return it's value this doesn't seem to work. Or maybe my issue is in how I handle parameters and arguments.

I would extremely appreciate someone could resolve this issue.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program
{
class Program
{

private string name;

static void Main(string[] args)
{
SetName();
Console.WriteLine("Name: " & ReturnName());
}
private static void SetName()
{
Console.WriteLine("What is your name?");
string name = Console.ReadLine();
}
public static string ReturnName(string name)
{
return name;
}
}
}


Errors:

Screenshot of Problem

Answer Source

As you have declared a class level variable 'name', you can initialize it once in the class scope and you can pass it to 'ReturnName' function as a parameter.

You don't need 'ReturnName' function at all. I have modified it like, 'SetName' to 'GetName' which returns the name where the user inputs. You can directly print in the main function like below,

  static void Main(string[] args)
    {
        string name = GetName();
        Console.WriteLine("Name: " + name);
    }


    private static string GetName()
    {
        Console.WriteLine("What is your name?");
        string name = Console.ReadLine();
        return name;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download