2

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?

elnigno
  • 1,751
  • 14
  • 37

2 Answers2

6

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?

They won't. The default access modifier for class members is private.If you want to make them public, you need to specify it explicitly.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
5

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.

Andrey Korneyev
  • 26,353
  • 15
  • 70
  • 71
  • 1
    Many thanks for your answer. So the only reason why you would declare a class public is so that you can instantiate an object of the class, but it does not mean that you can set the variables of the class? – Angela Marie-Daley Mar 03 '15 at 11:26
  • @AngelaMarie-Daley In fact, class needs to be public if you want to create instance of this class outside of assembly containing it. By default classes are internal (and can be instantiated inside the same assembly). And yes, access modifiers of class members are independent from class access modifier. – Andrey Korneyev Mar 03 '15 at 11:36