10

Edit, as per these comments:

Do you mean "Property" vs "Field"? public String S1; vs public String S2 { get; set; } – dana

Exactly dana, i mean the same. – Asad

Asad: you really need to try to use some other term to describe what you mean so that we can better understand your question. C# does not have global variables. The fields you can define in C# are not global - they are members of the class type. – dthorpe

Hi fellas,

Need your expert views over the difference between Field and Property. As in my project, I have used certain global variables which later on i changed to 'Properties' . My manager is asking what is the benefit of using Properties of variables instead of Fields.

Although I have replied him that Property provides a kind of secure/safe/indirect access to Field instead of modifying them directly if they are declared public or protected. But Please provide me with some more convincing arguments.

Thanks and Regards

@Asad: You should get your terminology right: Fields are not Global Variables, C# does not have global variables (as a few commenters mentioned: you can simulate global variables, but you should not do that).

Community
  • 1
  • 1
Asad
  • 521
  • 2
  • 13
  • 30
  • 2
    Global properties are still effectively global variables. Please post some example code of each approach for clarification, as I'm not really sure what you're talking about. If you are referring to static properties and static fields (the only kind of "global variables" in C#) either approach is just as bad in terms of "globalness" -- you should avoid global fields and properties whenever possible. – cdhowie Dec 15 '10 at 05:22
  • 1
    class GlobalVariables { public string MainOutputHexFile { get; set; } } – Asad Dec 15 '10 at 05:24
  • Does your manager have a background in development? I have been tainted by an educational background that lead me to believe global variables are an inherent evil. – Corey Sunwold Dec 15 '10 at 05:25
  • Above one the property of a variable 'mainOutputHexFile'. Other method of using this variable is to declare it 'Global'. As i need this variable througout my code. – Asad Dec 15 '10 at 05:26
  • Do you mean "Property" vs "Field"? public String S1; vs public String S2 { get; set; } – dana Dec 15 '10 at 05:28
  • Exactly dana, i mean the same. – Asad Dec 15 '10 at 05:31
  • Asad: that declaration is not a global variable. It is a class named GlobalVariable which defines a public property which stores its value in the object instance data. The get; set; is just shorthand that tells the C# compiler to automatically define storage for the property in the object instance. – dthorpe Dec 15 '10 at 05:31
  • Yes, i also mentioned the same that its a property. But what can be its significant adavantage over declaring it as a gloabal variable ? – Asad Dec 15 '10 at 05:35
  • 2
    Asad: you really need to try to use some other term to describe what you mean so that we can better understand your question. C# does not have global variables. The fields you can define in C# are not global - they are members of the class type. – dthorpe Dec 15 '10 at 05:53
  • But when i define these fields as public than they are like 'Global Variable' and can be accessed anywhere in the code. Just a quick question, which one is safer to use , a 'public property' of a variable or 'Public field'? – Asad Dec 15 '10 at 05:56
  • 2
    Properties HAVE to be public to be useful to other classes. And public or private, it's always a good rule of thumb to access values via properties rather than fields. – Paul Sasik Dec 15 '10 at 06:01
  • Why its always a good rule of thumb. Is there any logic/reason or advantage for this? – Asad Dec 15 '10 at 06:03

4 Answers4

11

The main advantage is that you can attach all sorts of functionality to a property such as validation, synchronization etc. You can't do that for a class field. For example, a field can throw BCL exceptions on assignment but it can't throw an exception that make sense with logic in your problem domain.

Also imagine trying to protect a field for thread synchronization. You have to write extra code in all the places in your code where the field is accessed. To do that with a property you can simply wrap the getter and setter with a lock in one place. (But beware! The ease of using lock in property getters and setters can give you a false sense of security if you're working with mutable types. See the accepted answer in this post.)

Now, you might think that validation and synchronization are not important to you for this particular value, and they may never be for this particular instance. But by using properties instead of direct field access is making your application much more maintainable in the future. (Suppose the value of an integer field suddenly needs to come from a source different from the original implementation and it needs to be converted from a string to an int. If you use properties to wrap the field then you make the change in one place and all the client code that uses that property does not need to change at all!)

Also, for managing information shared across many classes (global) take a look at the singleton pattern. But beware! Even though it looks neat and clean you can still get into trouble with it. Though if you really need global data you should use properties contained in a singleton. If nothing else, it's a good organization strategy.

To avoid issues with singletons or "global" data take a look at dependency injection as a much better alternative.

Community
  • 1
  • 1
Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
  • 1
    I agree. I think he might want to create a singleton. Check out http://csharpindepth.com/Articles/General/Singleton.aspx it shows you how to implement the singlton safely. – Beth Lang Dec 15 '10 at 05:41
  • @BitOff: A nice link and a great example of the synch idea from my recent edits. Also a great nod to the #1 wiz on SO, Jon Skeet. (He wrote that book: http://stackoverflow.com/users/22656/jon-skeet) – Paul Sasik Dec 15 '10 at 05:43
4

C# syntax doesn't have a "global variable" declaration. It has properties and fields, and static properties and fields.

If by "global variable" you mean a static field or static property, that is different from a property or field in that the static field or property is not stored in the object instance data, it is stored in global memory. The value assigned to a static field or property is accessible to all instances of that class, and all instances see the same value. A static field is the closest thing C# has to the notion of "global variable" found in other programming languages.

A non-static property or field stores its data in the object instance data, so each instance of the object has its own local copy. Modifying object1.A property will not affect the value of object2.A property.

dthorpe
  • 35,318
  • 5
  • 75
  • 119
3

Have a look at Properties (C# Programming Guide)

A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.

  • Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.
  • A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.
  • Properties that do not implement a set accessor are read only.
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • Actually need advantages of 'Property' over 'Global Variable'. A kind of comparison – Asad Dec 15 '10 at 05:22
  • Good reply, then what are the actual benefits of using property over gloabl variables? – Asad Dec 15 '10 at 05:28
  • "Global Variable" is more a term we used in a scripting language or in VB6 or something. In the strongly typed C#, all data is a property of an instance of a known class or data on a static class. Just like there aren't any free-floating functions, either, just methods and static methods. – zanlok Dec 15 '10 at 05:29
  • 1
    You have no control over public fields. The user of your class can set it to what ever value they wish. No validation, checks, etc... – Adriaan Stander Dec 15 '10 at 05:30
0

I prefer properties because then when I use them in code I know exactly which class was used to call them (ex. class.property = value). Public class variables can become a real pain and waste of time when you are trying to figure out where they came from during debugging.