I'm still finding my feet with C# and have a quick question that has been bugging me for a while.
Say I write a class and define a property as follows:-
public class Employee
{
string FirstName {get; set;}
}
class Program
{
private static object GetTheEmployee()
{
return new Employee{ FirstName = "Joe" }
}
}
Why is use of FirstName within the GetTheEmployee method inaccessible, but when I change the FirstName 'string' variable in the Employee class to 'public string' instead, it is accessible from the Program class.
I would have thought that if I declare the class' access modifier as public, then all variables within in the class will also be public by default?
The fact you've declared class as public
doesn't mean all members of class will be also public.
By default class members (fields, properties, methods and so on) has private
access modifier, so if you haven't explicitly declared your property as public
(or protected, internal and so on), it will be private.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments