Reputation: 135
I come from Java and i have learned to never set a Variable public. Always make a variable private and make her accessable over setter and getter methods.
I started with C# the last days and im actually getting problems with this:
String Name { get; set; }
From other classes i can not access to the variable "Name"
so i thought this might be a good solution:
String Name { public get; public set; }
but yes ... does not work.
Do i have to make every variable public?
Upvotes: 0
Views: 727
Reputation: 7918
@Selman22 already gave you a concise and accurate answer, extended with comments by @Mike Christensen. (essentially, you are talking about Properties
). You may also consider an option available in C# to use Internal
access modifier, applied to types or members that are accessible only within files in the same assembly, so less visible from the outside world.
Best regards,
Upvotes: 0
Reputation: 469
These are properties, not fields. Properties in C# are the same as getter and setter methods in Java. To make them public you should have public string Name { get; set;}
.
Generally you shouldn't have too many of these on your classes as it breaks encapsulation and is symptomatic of a bad design.
Upvotes: 1
Reputation: 22638
You are defining a property, not a field. This is equivalent to creating a getName
and setName
in Java and an associated private field.
The syntax you are using is shorthand for doing this.
To make it accessible set the property to public.
public String Name { get; set; }
If you don't want the set method to be accesible you can mark it private:
public String Name { get; private set; }
This will cause the compiler to create code equivalent to the following:
private String _name;
public String GetName()
{
return _name;
}
private void SetName(String name)
{
_name = name;
}
Upvotes: 5
Reputation: 101681
You need to make property public
public String Name { get; set; }
Class members are private
by default.
Upvotes: 4