简体   繁体   中英

Private/Public Variables in C#

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?

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;
}

You need to make property public

public String Name { get; set; }

Class members are private by default.

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;} 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.

@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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM