Click here to Skip to main content
15,907,329 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi friends.
i want to know that declaring global variable in this fashion is same or not..

1.
C#
 private static string ab;
public static string abc
{
    get { return ab; }
    set { ab = value; }
}

2.
C#
public static string abc;
Posted
Updated 26-Jul-11 22:47pm
v2

Yes! In between, you might want to read this article about public variables vs properties.

http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html[^]
 
Share this answer
 
To an external client that uses your code, it may not make much difference. But encapsulating your variables in a Property enables you to validate its value. For example, if there is an Age field, you can restrict its values betweeen 1 and 120 or so. Using public variables will not allow you to validate its values.

Here's an example:
C#
int _age = 0;
public int Age { 
    get { 
        return _age; 
    }
    set {
        if (_age < 0 || _age > 120) { 
            throw new ArgumentException("Valid values for Age is between 0 and 120."); 
        } 
        _age = value; 
    }
}
 
Share this answer
 
v2
Comments
advancedansh 27-Jul-11 4:58am    
thanks but can you give me the example of this that how can i restrict the property value
[no name] 27-Jul-11 6:30am    
see my updated answer for an example.
advancedansh 27-Jul-11 6:48am    
thanks bro..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900