C++/CLI shorthand properties
Asked Answered
V

3

24

How does a developer do the equivalent of this in managed c++? :

c# code

public String SomeValue
{
  get;
  set;
}

I've scoured the net and found some solutions, however it is hard to distinguish which is the correct (latest, .NET 3.5) way, given the colourful history of getters/setters and managed c++.

Thanks!

Vise answered 15/12, 2009 at 14:26 Comment(4)
Managed C++ is out of date. C++/CLI is the current method.Cheshire
Sorry, C++/CLI is what I am using. I still use the old name :(Vise
DanDan: C++/CLI is an entirely different language. While it's a successor to Managed C++, Managed C++ is not really its old name.Weisman
I'll make sure I use the correct name for the correct language.Vise
W
39

Managed C++ does not support automatic properties. You should manually declare a backing field and the accessors:

private: String* _internalSomeValue;
public:
__property String* get_SomeValue() { return _internalSomeValue; }
__property void set_SomeValue(String *value) { _internalSomeValue = value; }

C++/CLI supports automatic properties with a very simple syntax:

public: property String^ SomeValue;

Update (reply to comment):

In C++/CLI, you cannot control the accessibility of each accessor method separately when you use the automatic property syntax. You need to define the backing field and the methods yourself:

private: String^ field;
property String^ SomeValue { 
   public: String^ get() { return field; }
   private: void set(String^ value) { field = value; }
}
Weisman answered 15/12, 2009 at 14:30 Comment(1)
In the C++/CLI version, how would I make the setter private, for example?Vise
W
20

In C++/CLI you would do just:

property String^ SomeValue;
Wyne answered 15/12, 2009 at 14:30 Comment(0)
C
5

Just to give you more search terms, this is called a trivial property

Camelopardalis answered 15/12, 2009 at 14:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.