Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter property with arguments

Tags:

c#

properties

I guess I've seen it somewhere before, but now I can't remember nor find it. Is there a way to make a getter property with arguments?

I mean, as I can convert "float getSize();" to "float Size":

float getSize() {     return this.size; }  float Size {     get { return this.size; } } 

Then, could I convert, for example, "float getSize(String unit);" to "float Size(String unit)" or something like that?

float getSize(String unit) {     return this.size; }  float Size(String unit) {     get {         if (unit == Unit.Meters)             return this.size/100;         else             return this.size;     } } 

I think there's no really problem of using function at all, but may look better this way :P

like image 516
Dane411 Avatar asked May 22 '11 14:05

Dane411


People also ask

Can a python property take arguments?

The property() method in Python provides an interface to instance attributes. It encapsulates instance attributes and provides a property, same as Java and C#. The property() method takes the get, set and delete methods as arguments and returns an object of the property class.

Do getters take parameters?

The getter method returns the value of the attribute. The setter method takes a parameter and assigns it to the attribute. Getters and setters allow control over the values.

What is getter and setter properties?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.

What is a getter function?

The getter function is used to retrieve the variable value and the setter function is used to set the variable value. Remember: You can directly access public member variables, but private member variables are not accessible. Therefore, we need getter functions.


2 Answers

To answer the question: No, it is not possible, and as already pointed out, a getter with a parameter would look just like a method.

The thing you are thinking about might be an indexed default property, which looks like this:

class Test {     public string this[int index]      {         get { return index.ToString(); }      } } 

This allows you to index into an instance of Test, like this:

Test t = new Test(); string value = t[1]; 
like image 123
driis Avatar answered Sep 20 '22 06:09

driis


Interestingly, having a property with parameter is possible in VB.NET, like this:

Public ReadOnly Property oPair(param As String) As Result   Get      'some code depends on param   End Get End Property 

It's not superior to a regular function, but sometimes it is nice to have such a possibility.

like image 27
Damian Kobak Avatar answered Sep 23 '22 06:09

Damian Kobak