Reputation: 5236
I make a wrapper for my application data. But first, my code:
public class FakeData
{
private List<User> users { get; set; }
private List<Project> projects { get; set; }
public FakeData()
{
users = new List<User>
{
//Some Data here
};
projects = new List<Project>
{
//Some data here
};
}
public void Initialize() => context = new FakeData();
public List<User> GetUsers() => context.users; //i get an error here
private FakeData context { get; set; }
}
What i want to do, is wrapped FakeData()
class. I want to have private lists and object state in this class. Why VS telling me, that type List<User>
is less available than method GetUsers()
? How to make it properly when i want to have acces to object and lists only by accces public methods?
Thanks for any advices
EDIT
Thanks for your answers, it was really helpful!
What i want to get by wrapping my FakeData()
class is to not make public propertys from Users
and Projects
. I want to have acces to it only by public methods that i will write in FakeData
class
Upvotes: 1
Views: 328
Reputation: 62488
You cannot access the context
's current instance users
property outside that even in the other instance of same type.
As you have defined users
private it can only be accessed from within the context
and you cannot access it outside that.
While you are trying to access the users
property.
Private access is the least permissive access level. Private members are accessible only within the body of the class or the struct in which they are declared
See more examples of these here
You can change the set
to private if you don't want it to be modified outside the class :
public List<User> users { get; private set; }
Now your code would work fine and you can read the users
property.
Upvotes: 1
Reputation: 2107
Why VS telling me, that type List is less available than method GetUsers()?
You need to modify your User
class to ensure it is public, so it is at least as available as your FakeData
class which is referencing it.
public class User
{
}
How to make it properly when i want to have access to object and lists only by access public methods?
Expose your properties as public.
public class FakeData
{
public List<User> Users { get; private set; }
public List<Project> Projects { get; private set; }
public FakeData()
{
Users = new List<User>
{
//Some Data here
};
Projects = new List<Project>
{
//Some data here
};
}
}
Upvotes: 1
Reputation: 24222
Looks like class User
is not public, you need to change that. Reason: a method that is public
can only return things that are also public
.
Upvotes: 1