What Should a C++ Getter Return

What should a C++ getter return

You can provide both const and non-const versions:

MyType       & MyClass::getMyType()       { return mMyType; }
MyType const & MyClass::getMyType() const { return mMyType; }

I wouldn't provide a pointer version, since that implies that the return value might be the null pointer, which it can never be in this instance.

The real point, however, is that you are basically giving the caller direct access to the internal object. If this is your intent, then you may as well make the data member public. If it isn't, then you will need to work harder to hide the object.

One option is to retain the MyType const & accessor, but provide more indirect means to modify the internal object (setMyType(…) or something more tailored to the semantics that you are trying to express at the level of the containing class).

Is it best practice for a C# property getter to return a new object?

Creating a new object is a good defensive strategy to prevent modifications of your object's internals.

However, it should be applied only when the object that you are returning is a mutable, and is not a struct (which should be immutable anyway [why?]).

CGSize is a struct, so you are creating a new value-typed object here. This is exactly what you should do when you do not store the Size.

Why should a C# property getter not read from a DB?

Because retrieving data from a database could cause any number of exceptions, and property getters, as a rule, should never throw exceptions.

The expected behavior of a property getter is just to return a value; if it's actually doing a lot more than that, it should be a method.

Microsoft's guide for Property Design explains the reasons:
https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/property

Getter and Setter declaration in .NET

Properties are used to encapsulate some data. You could use a plain field:

public string MyField

But this field can be accessed by all outside users of your class. People can insert illegal values or change the value in ways you didn't expect.

By using a property, you can encapsulate the way your data is accessed. C# has a nice syntax for turning a field into a property:

string MyProperty { get; set; }

This is called an auto-implemented property. When the need arises you can expand your property to:

string _myProperty;

public string MyProperty
{
get { return _myProperty; }
set { _myProperty = value; }
}

Now you can add code that validates the value in your setter:

set
{
if (string.IsNullOrWhiteSpace(value))
throw new ArgumentNullException();

_myProperty = value;
}

Properties can also have different accessors for the getter and the setter:

public string MyProperty { get; private set; }

This way you create a property that can be read by everyone but can only be modified by the class itself.

You can also add a completely custom implementation for your getter:

public string MyProperty
{
get
{
return DateTime.Now.Second.ToString();
}
}

When C# compiles your auto-implemented property, it generates Intermediate Language (IL). In your IL you will see a get_MyProperty and set_MyProperty method. It also creates a backing field called <MyProperty>k_BackingField (normally this would be an illegal name in C# but in IL it's valid. This way you won't get any conflicts between generated types and your own code). However, you should use the official property syntax in C#. This creates a nicer experience in C# (for example with IntelliSense).

By convention, you shouldn't use properties for operations that take a long time.

Correct way to return string reference in getter

Either return a copy or a const reference:

std::string get() const         { return s_; }
const std::string& get() const { return s_; }

How do I call a getter or setter in C#

localMyClass.myVal = 42;

Getters and setters let you treat the values like public properties. The difference is, you can do whatever you want inside the functions that do the getting and setting.

Examples:

store other variables

private int _myVal, myOtherVal;
public int MyVal { get; set { _myVal = value; myOtherVal++; } }

make numbers up / return constants

public int MyVal { get { return 99; } set; }

throw away the setter

private int _myVal;
public int MyVal { get { return _myVal; } set { ; } }

In each of these cases, the user will feel like it's just a public data member, and simply type

localMyClass.myVal = 42;
int i = localMyClass.myVal;

The gettors and settors let you make an implementation of your own. Also, as Hogan says, "There are a number of libraries and add-ons [e.g. MVC.NET] that require you to use getter and setter functions" - even if it's for the trivial {get; set;} case.

How to Return Object through getter method in Java

public Student getStudent(){
return this;
}

But I do hope you understand that this makes no sense at all. In order to be able to return the 'this' of that instance, you would already need the instance to be able to call the method getStudent()

Or do you mean you want to return a cloned object?

What is the best way to give a C# auto-property an initial value?

In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).

Example of attributes that impact the IL are ThreadStaticAttribute, CallerMemberNameAttribute, ...

Automated property with getter only, can be set, why?

This is a new C# 6 feature, "Getter-only auto-properties", also known as "Auto-Property Initializers for Read-Only Properties" as discussed in this MSDN magazine article 'C# : The New and Improved C# 6.0' by Mark Michaelis and in the C# 6.0 draft Language Specification.

The read-only field's setter is only accessible in the constructor, in all other scenarios the field is still read only and behaves as before.

This is a convenience syntax to reduce the amount of code you need to type and to remove the need to explicitly declare a private module level variable to hold the value.

This feature was seen as important as, since the introduction of Auto-Implemented Properties in C#3, mutable properties (those with a getter and setter) had become quicker to write than immutable ones (those with only a getter), meaning people were being tempted to use mutable properties to avoid having to type the code for a backing field usually required for read-only properties. There is more discussion of Auto-Implemented properties in the relevant section of the Microsoft C# Programming Guide.

This blog post, '#1,207 – C# 6.0 – Auto-Property Initializers for Read-Only Properties' by Sean Sexton Has a good explanation and example as follows:

Prior to C# 6.0, if you wanted a read-only (immutable) property, you’d
typically use a read-only backing field that is initialized in the
constructor, as shown below.

public class Dog 
{
public string Name { get; set; }

// DogCreationTime is immutable
private readonly DateTime creTime;
public DateTime DogCreationTime
{
get { return creTime; }
}

public Dog(string name)
{
Name = name;
creTime = DateTime.Now;
}
}

In C# 6.0, you can use auto-implemented properties to implement a
read-only property. You do this by using an auto-property
initializer. The result is much cleaner than the above example, where
we had to explicitly declare a backing field.

public class Dog
{
public string Name { get; set; }

// DogCreationTime is immutable
public DateTime DogCreationTime { get; } = DateTime.Now;

public Dog(string name)
{
Name = name;
}
}

More details can also be found in the dotnet Roslyn repo on GitHub:

Auto-properties can now be declared without a setter.

The backing field of a getter-only auto-property is implicitly
declared as readonly (though this matters only for reflection
purposes). It can be initialized through an initializer on the
property as in the example above. Also, a getter-only property can be
assigned to in the declaring type’s constructor body, which causes the
value to be assigned directly to the underlying field:

This is about expressing types more concisely, but note that it also
removes an important difference in the language between mutable and
immutable types: auto-properties were a shorthand available only if
you were willing to make your class mutable, and so the temptation to
default to that was great. Now, with getter-only auto-properties, the
playing field has been leveled between mutable and immutable.

and in the C# 6.0 draft Language Specification (NB: The language specification is final as far as Microsoft are concerned, but it is yet to be approved as a EMCA/ISO standard, hence the 'draft'):

Automatically implemented properties

An automatically implemented property (or auto-property for short), is
a non-abstract non-extern property with semicolon-only accessor
bodies. Auto-properties must have a get accessor and can optionally
have a set accessor.

When a property is specified as an automatically implemented property,
a hidden backing field is automatically available for the property,
and the accessors are implemented to read from and write to that
backing field. If the auto-property has no set accessor, the backing
field is considered readonly (Readonly fields). Just like a readonly
field, a getter-only auto-property can also be assigned to in the body
of a constructor of the enclosing class. Such an assignment assigns
directly to the readonly backing field of the property.

An auto-property may optionally have a property_initializer, which is
applied directly to the backing field as a variable_initializer
(Variable initializers).

Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?

I'm surprised noone mentioned the field keyword, it is exactly what you are asking for (what you would use instead of [backing field] in your example). It was supposed to be shipped with C# 10. It seems it is going to be shipped with C# 11 instead (?)

Search for Field Keyword here.



Related Topics



Leave a reply



Submit