-2

I wonder, in C# I could declare ( often I see such style from code reviews ) like this:

string myVarName
{
    get
    {
        return myVarName;
    }
    set
    {
        myVarName = value;
    }
}

But many people tell, that is better, than just string myVarName; declaration as not a property.

I'm becoming confused sometimes, because I often see such a style in code listings.

Why is it better? Are properties inlined in addition to the hint to the JIT-compiler that the function should be compiled inline into where it is used avoiding a function call overhead?

Or I can win with some performance?

As for the code-style, I like more simple variable declaration not in property style.

As for the property, I can see only the best advantage in some default manipulations/triggers. E.g.: I need to store the half value in property from incoming value or smth like that...

Maybe I'm not right at all. Am I right or not?

Thanks!

Secret
  • 2,627
  • 7
  • 32
  • 46

1 Answers1

3

Actually it's not about coding style, you should use properties in the way it benefits you the most.

I use properties like this:

public string Name {get;set;}

When I don't need any special implementation

And I use them like this:

public string Name
{
    get
    {
        return name;
    }
    set
    {
        name = value.toLower();
    }
}

When I need to do something with the value before assigning it.

I also encourage you to use properties not because is "better", but because it's more flexible.

Think for a second that you just used public variables. If you ever need to add some kind of validation, you would need to update every single class that instantiates the class you want to modify. With properties you wouldn't need any external change.

As for the performance concern, don't worry about it. I don't think you would gain any performance boost avoiding Properties and even if you do, it would be so tiny that is by no means worth it, because you are discarding a really valuable feature you may need in future and can be extremely painful to update.