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.
- Syntax problem: Every method must have a return type. Either a real type like
int
or thevoid
keyword.public int Index()
- 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:
- Passing value through a class field (your "global" variable).
This requires you to callprivate int _userId; public void SetUserId() // `void` means that the method is not returning a value. { _userId = 10; } public void PrintUserId() { Console.WriteLine(_userId); }
SetUserId();
before callingPrintUserId();
- 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()); }
- Combine the two previous approaches
private int _userId; public void SetUserId() { _userId = 10; } public int GetUserId() { return _userId; } public void PrintUserId() { Console.WriteLine(GetUserId()); }
- 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.
A property having no additional logic besides assigning and returning a value can also be implemented as an auto-property.private int _userId; public UserId { get { return _userId; } set { _userId = value; } } public void PrintUserId() { Console.WriteLine(UserId); }
The caller would have to do something like this:public int UserId { get; set; } // A hidden field is automatically created.
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;