Asked  7 Months ago    Answers:  5   Viewed   33 times

Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?

We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:

public void SetLabel(string text)
{
    Label.Text = text;
}

In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.

I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.

 Answers

21

From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:

In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

Tuesday, June 1, 2021
 
Ticksy
answered 7 Months ago
31

You should not worry about the extra code needed for accessing fields via properties, it will be "optimized" away by the JIT compiler (by inlining the code). Except when it is too large to be inlined, but then you needed the extra code anyway.

And the extra code for defining simple properties is also minimal:

public int MyProp { get; set; } // use auto generated field.

When you need to customize you can alway define your own field later.

So you are left with the extra layer of encapsulation / data protection, and that is a good thing.

My rule: expose fields always through properties

Tuesday, June 8, 2021
 
Pradip
answered 7 Months ago
44

Really, you need to back up and read some of the links posted above. But as a quick example:

var house = {} ;

house.isDoorOpen = false ;

house.openDoor = function(){
    house.isDoorOpen = true ;
}

Here house is the object. It has a property: house.isDoorOpen. Here, it is more like an adjective. Either the door is open (true) or closed (false). As it sounds, it describes a property of the house.

Also, it has a method openDoor (which is used like this: house.openDoor() ). That's something that it can do. In this case, the action openDoor affects the isDoorOpen property, making it true.

Wednesday, July 14, 2021
 
lewiguez
answered 5 Months ago
59

This feature is called Auto implemented properties and introduced with C# 3.0

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

class Customer
{
    // Auto-Impl Properties for trivial get and set 
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

For your question

What is the difference between the two?

In your case, none. Since you are not doing anything while setting or retrieving the value, but suppose you have want to do some validation or want to perform other types of check then :

private int someInt;
public int RetInt
{
    get
    {
        if (someInt > 0)
            return someInt;
        else
            return -1;
    }
    set { someInt = value; } // same kind of check /validation can be done here
}

The above can't be done with Auto implemented properties.

One other thing where you can see the difference is when initializing a custom class type property.

If you have list of MyClass Then in case of Normal property, its backing field can be initialized/instantiated other than the constructor.

private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
    get { return list; }
    set { list = value; }
}

In case of Auto implemented property,

public List<MyClass> SomeOtherList { get; set; }

You can only initialize SomeOtherList in constructor, you can't do that at Field level.

Wednesday, August 11, 2021
 
Amber
answered 4 Months ago
60

No, there's not a way to declare a property on a module in TypeScript using any documented language features.

You can do it in several slightly round-about techniques.

A module can extend an existing class or function. So, I've created a class with a static property, and then later created a module that uses the same name as the class.

class My
{
    static get Value():Number {
        return 42;
    }
}

module My {
    var works: boolean = true;
}

alert(My.Value);

It does generate one oddity in the JavaScript generated code that you wouldn't do manually (and should be removed by most optimizers anyway) ... it will redeclare the variable My when the module is created. This does not cause a run-time issue as the variable was already lifted in JavaScript and will not conflict with the first usage.

Here's another option:

module Global {
    class Inner {
        get Value():Number {
            return 42;
        }       
    }   
    export var My;
    My = new Inner();
}

var My = Global.My;
alert(My.Value);

While it presents an extra namespace, you can manipulate it however you'd like and use the inner class or change it as needed. This way, the My variable is global, just like it would be as a module.

Thursday, November 4, 2021
 
Elliott Frisch
answered 1 Month ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share