Does C++11 Have C#-Style Properties

C#-like properties in native C++?

In .NET properties are syntactic sugar for the real get and set functions which are emitted behind the scenes (in fact they are more than syntactic sugar because properties are emitted in the resulting IL and could be used with Reflection). So in C++ you would need to explicitly write those functions as there's no such notion as property.

C# Equivalent for C++ Macros and using Auto Properties

This might make things a bit neater, you could add this method to introduce some reuse:

protected ComplexType _propertyName;
public ComplexType PropertyName
{
get
{
return GetProperty(ref _propertyName);
}
}
.
.
private T GetProperty<T>(ref T property) where T : new()
{
if (property == null)
property = new T();
return property;
}

Does C# have extension properties?

For the moment it is still not supported out of the box by Roslyn compiler ...

Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.

But it will ...

There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.

However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.

Moreover you can use a workaround

As specified in this article, you can use the TypeDescriptor capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.

It's a little bit different from just syntactic sugar adding a possibility to define an extended property like
string Data(this MyClass instance) as an alias for extension method
string GetData(this MyClass instance) as it stores data into the class.

I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.

And feel free to contribute as the software of tomorrow will come from the community.

Update: August 2016

As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:

Extension properties: we had a (brilliant!) intern implement them over
the summer as an experiment, along with other kinds of extension
members. We remain interested in this, but it’s a big change and we
need to feel confident that it’s worth it.

It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.

Update: May 2017

The extension members has been closed as duplicate of extension everything issue which is closed too.
The main discussion was in fact about Type extensibility in a broad sense.
The feature is now tracked here as a proposal and has been removed from 7.0 milestone.

Update: August, 2017 - C# 8.0 proposed feature

While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:

public interface IEmployee 
{
public decimal Salary { get; set; }
}

public class Employee
{
public decimal Salary { get; set; }
}

public extension MyPersonExtension extends Person : IEmployee
{
private static readonly ConditionalWeakTable<Person, Employee> _employees =
new ConditionalWeakTable<Person, Employee>();

public decimal Salary
{
get
{
// `this` is the instance of Person
return _employees.GetOrCreate(this).Salary;
}
set
{
Employee employee = null;
if (!_employees.TryGetValue(this, out employee)
{
employee = _employees.GetOrCreate(this);
}
employee.Salary = value;
}
}
}

IEmployee person = new Person();
var salary = person.Salary;

Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...).
For this, you can still use the TypeDescriptor/ConditionalWeakTable technique described earlier and with the property extension, hides it under a nice property.

Syntax is still subject to change as implies this issue. For example, extends could be replaced by for which some may feel more natural and less java related.

Update December 2018 - Roles, Extensions and static interface members

Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:

Roles allow interfaces to be implemented on specific values of a given
type. Extensions allow interfaces to be implemented on all values of a
given type, within a specific region of code.

It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:

public extension ULongEnumerable of ulong
{
public IEnumerator<byte> GetEnumerator()
{
for (int i = sizeof(ulong); i > 0; i--)
{
yield return unchecked((byte)(this >> (i-1)*8));
}
}
}

then you would be able to do this:

foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
WriteLine($"{e.Current:X}");
}

And for a static interface:

public interface IMonoid<T> where T : IMonoid<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}

Add an extension property on int and treat the int as IMonoid<int>:

public extension IntMonoid of int : IMonoid<int>
{
public static int Zero => 0;
}

Is there any C# naming convention for a variable used in a property?

Per Microsoft's naming conventions, the proper way would be:

private string fubar;
public string Fubar { get { return fubar; } set { fubar = value; } }

However, many people prefer to prefix the private field with an underscore to help minimize the possibility of miscapitalizing and using the field when they meant to use the property, or vice versa.

Thus, it's common to see:

private string _fubar;
public string Fubar { get { return _fubar; } set { _fubar = value; } }

The approach you take is ultimately up to you. StyleCop will enforce the former by default, whereas ReSharper will enforce the latter.

In C# 6, there is new syntax for declaring default values for properties or making read-only properties, lessening the need for properties with backing fields that don't have any special additional logic in the get and set methods. You can simply write:

public string Fubar { get; set; } = "Default Value";

or

public string Fubar { get; } = "Read-only Value";

Defacto standard C++11 coding style?

Does C++ use camelCase instead?

There is no single standard style in the C++ world. There are quite a few common styles, but not a single style that exists everywhere. In general, the best you can hope for is consistency in your own group, and that each library you use stays consistent within itself.

PascalCase is rare in C++ libraries. camelCase is more common, but it's also very common to have underscore_separated naming. The latter is probably the most common, since the C++ Standard Library uses underscore_separation in naming.

How to use C#-like attributes in C++

To "attach additional behavior to a class in runtime" in most any OO language I recommend the Strategy design pattern -- have the class (and/or its instances) hold (through a pointer in C++, a [reseatable] reference in other languages) an instance of a suitable interface / abstract class known as the "strategy interface" (with one method [virtual in C++ of course, non-final in languages that have final, etc -- IOW, an overridable method!-)] per point of extensibility), and generally supply getter and setter methods (or properties or whatever's appropriate to the specific language) to access and change that instance.

Lastly, the class or instance must delegate all appropriate functionality through the methods of the strategy interface instance it's holding.

I often recommend this "high-ceremony" approach (for this specific purpose) even in dynamic languages such as Python or Ruby which would also allow more informal approaches via duck typing and the ability of an object of class to directly reach into the internals of another -- such dynamic abilities are generally speaking quite useful, but for this specific purpose (as I think of "changing a class behavior at runtime") a more highly architected and controlled approach, in my experience, leads to better-maintainable and clearer code (this bit is controversial: many developers in dynamic-language communities like "monkey patching" approaches even in such situations, but a dozen years of successful development practice in dynamic languages, mostly Python, have made me otherwise inclined).

In appropriate case you can modify the fundamental Strategy DP approach in various ways; for example, when the modifiable functionality falls neatly into a few cohesive groups, it's best to "fragment" the Strategy object into several simple and cohesive ones (DrawingStrategy, PersistenceStrategy, BusinessRulesStrategy, and so forth).

This whole approach does not take the place of performing proper analysis and consequently proper design, as it won't allow extension of a class functionality along an axis that was not originally taken into consideration; rather, the approach is intended as a proper way to architect a well-thought-out design, providing "hooks" for extensibility in a well-controlled manner. If new considerations come into play it may still well be necessary to iterate and perfect the classes' design to cover such new ideas. But then, iterative development (including tweaks and extensions to the original design) is inevitable in any rich, complex real-world project -- the Strategy DP is just one arrow in your quiver to help make the process more orderly and effective.



Related Topics



Leave a reply



Submit