Reputation: 2494
i have created Solution which contain 3 Projects like.
//Project Name: ClientProject
public class UserDetails
{
public static int ID { get; set; }
public static string Name { get; set; }
public static string Email { get; set; }
}
This above class should be set once, When user logged in and after that i would like to access these details across entire solution.
Like Administration, SalesInfo projects.
//Project Name: Administration
public class Admin
{
public static UserDetails Details
{
//Here i would like to return UserDetails
get;
}
public static int DepartmentID { get; set; }
public static string Phone { get; set; }
public static string Head { get; set; }
}
//Project Name: SalesInfo
public class Sales
{
public static UserDetails Details
{
//Here i would like to return UserDetails
get;
}
public static DateTime Date { get; set; }
public static string Item { get; set; }
public static int Price { get; set; }
}
Any Answer, Comments or Suggestions would be highly appreciated
Upvotes: 0
Views: 116
Reputation: 4371
Use a kind of singleton as mentioned by Groo.
public class UserDetails
{
public static int ID { get; private set; }
public static string Name { get; private set; }
public static string Email { get; private set; }
private static UserDetails _userDetails;
private UserDetails(int id, string name, string email)
{
ID = id;
Name = name;
Email = email;
}
public static UserDetails CreateUserDetails(int id, string name, string email)
{
if (_userDetails != null)
{
throw new MyException("Second call to UserDetails.CreateUserDetails!");
}
_userDetails = new UserDetails(id, name, email);
return _userDetails;
}
public static UserDetails GetUserDetails()
{
if (_userDetails == null)
{
throw new MyException("Not yet created by calling UserDetails.CreateUserDetails!");
}
return _userDetails;
}
}
After log-in you call UserDetails.CreateUserDetails(...)
to set the global object.
To get details call GetUserDetails()
.
Upvotes: 1
Reputation: 1062
Normally property uses private field to store the data. This behavior added during compile time and is hidden for the developer while coding. Static method/property can't access private variables/fields in a class.
I recommend to use singleton pattern.
public class UserDetails
{
private static UserDetails _instance;
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
private UserDetails() {}
public static UserDetails Instance
{
get
{
if (_instance == null)
{
_instance = new UserDetails();
}
return _instance;
}
}
}
And you can consume like this,
//Project Name: Administration
public class Admin
{
public static UserDetails Details
{
get
{
return UserDetails.Instance;
}
}
public static int DepartmentID { get; set; }
public static string Phone { get; set; }
public static string Head { get; set; }
}
Upvotes: 1