Home > Blockchain >  how to use global variable and update it in other method
how to use global variable and update it in other method

Time:11-16

public int userID;
//global variable 
        
        
        public Index()
        {
            userID = 10;
            return userID;
        }
        
        public TaskCompleted()
        {
            Console.WriteLine(Index())
        }

i want the userID to be accessed in each and every method and can we updated anywhere

CodePudding user response:

Your Index method has two problems.

  1. Syntax problem: Every method must have a return type. Either a real type like int or the void keyword.
    public int Index()
    
  2. Semantic problem. At every call it sets userID and returns it. Why store the value in this variable? It will be replaced by a new value at the next call and could just be a local variable (i.e., a variable inside the method) or be dismissed completely. But maybe your example was simply not complete.

Let's try different approaches:

  1. Passing value through a class field (your "global" variable).
    private int _userId;
    
    public void SetUserId() // `void` means that the method is not returning a value.
    {
        _userId = 10;
    }
    
    public void PrintUserId()
    {
        Console.WriteLine(_userId);
    }
    
    This requires you to call SetUserId(); before calling PrintUserId();
  2. Let the method return the value.
    public int GetUserId() // `int` means that the method is returning an `int` value
    {
        return 10;
    }
    
    public void PrintUserId()
    {
        Console.WriteLine(GetUserId());
    }
    
  3. Combine the two previous approaches
    private int _userId;
    
    public void SetUserId() 
    {
        _userId = 10;
    }
    
    public int GetUserId()
    {
        return _userId;
    }
    
    public void PrintUserId()
    {
        Console.WriteLine(GetUserId());
    }
    
  4. C# has a concept called "property". A property is a set of "Get" and "Set" methods, just as in the previous example, but with as special syntax.
    private int _userId;
    public UserId
    {
       get { return _userId; }
       set { _userId = value; }
    }
    
    public void PrintUserId()
    {
        Console.WriteLine(UserId);
    }
    
    A property having no additional logic besides assigning and returning a value can also be implemented as an auto-property.
    public int UserId { get; set; }  // A hidden field is automatically created.
    
    The caller would have to do something like this:
    var obj = new MyClass();
    obj.UserId = 10;
    obj.PrintUserId();
    

CodePudding user response:

You can use a static property of a static class:

public static class Globals
{
    public static int UserID {get; set;}
}

Usage: var userId = Globals.UserID;

  • Related