Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the advantage of using private variables in C#

Sample code (alternative code is below),

// person.cs
using System;
class Person
{
    private string myName ="N/A";

    // Declare a Name property of type string:
    public string Name
    {
        get 
        {
           return myName; 
        }
        set 
        {
           myName = value; 
        }
    }
    public override string ToString()
    {
        return "Name = " + Name;
    }

    public static void Main()
    {
        Person person = new Person();
        Console.WriteLine("Person details - {0}", person);
        person.Name = "Joe";
        Console.WriteLine("Person details - {0}", person);

    }
}

Can't we directly write, changing myName from private to public, no requirement to declare another public variable Name and no need to use get and set?

alternative code

    // person.cs
    using System;
    class Person
    {

        public string myName ="N/A";

        public override string ToString()
        {
            return "Name = " + myName;
        }

        public static void Main()
        {
            Person person = new Person();
            Console.WriteLine("Person details - {0}", person);
            person.myName = "Joe";
            Console.WriteLine("Person details - {0}", person);

        }
    }
like image 384
michael Avatar asked Jun 19 '13 08:06

michael


People also ask

What is the purpose of private variables?

In general, private variables are those variables that can be visible and accessible only within the class they belong to and not outside the class or any other class. These variables are used to access the values whenever the program runs that is used to keep the data hidden from other classes.

Why use private variables instead of public?

Class variables that are declared as private can not be referred to from other classes, they are only visible within their own class. It is considered better programming practice to use private rather than public class variables, and you should aim to do this in the remainder of the course.

What is the purpose and benefit of private members in a class?

These classes have no public setters at all, which guarantees that their objects, once created, will not change their state. This enables a lot of performance optimizations, as well as makes them easier to use in e.g. multithreaded programs, ORM etc. Save this answer.

Are there private variables in C?

If you want private variables in c, there are a number of techniques that can approximate a private variable, but the C language actually doesn't have a "protection" concept that extends to private, public, protected (as C++ does).


2 Answers

Externally visible properties are better than fields because:

  • Properties allow better encapsulation. Fields are a fixed implementation and allow direct access from consumers. Properties:

    • are loosely coupled (since underlying field can change from variable to database anytime)

    • allow custom logic (validation, event notification, lazy loading, etc.)

    • control access (since logic can be built in get/set, even declared read-only or write-only).

  • Fields cannot be used in interfaces. This is an impediment to Test Driven Development (interface first).

  • Automatic or Auto-Implemented Properties are as easy to declare as fields and also optimized to perform on par with fields. See here.

  • Declaring an externally visible field (public, protected, protected internal) is a FxCop violation. See rule CA1051.

  • Changing a field to a property is a breaking change, since the calling code needs to be recompiled (applies to binary serialization as well).

  • Properties are recognized by many libraries in .NET for tasks such as XML serialization, WPF bindings, ASP.NET 2-way binding, etc. and also by Visual Studio designer.

like image 65
Channs Avatar answered Sep 23 '22 12:09

Channs


You are cracking up one of the bases of OOP -> information hiding / encapsulation

By defining your properties as public you give EVERYONE access to them and they can be changed (corrupted) as desired. This way you cannot promise that your objects will be in a consistent state all of the time.

From Wikipedia

In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination[1][2] thereof:
- A language mechanism for restricting access to some of the object's components.[3][4]
- A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.[5][6]

Some programming language researchers and academics use the first meaning alone or in combination with the second as a distinguishing feature of object oriented programming, while other programming languages which provide lexical closures view encapsulation as a feature of the language orthogonal to object orientation.

The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus, information hiding is defined as a separate notion by those who prefer the second definition.

like image 27
bash.d Avatar answered Sep 22 '22 12:09

bash.d