in

ASP.NET Weblogs

This Blog

Syndication

Christian Nagel's OneNotes

.NET Training, Consulting, Coaching - C#, Web Services, Enterprise Services, ASP.NET, Whidbey, Longhorn and More!

Properties with C++/CLI

C++/CLI was influenced by C#, but it also has a shorter syntax for properties.

This is the C# syntax of properties:

private string lastname;
public string Lastname
{
   get
   {
      return lastname;
   }
   set
   {
      lastname = value;
   }
}

The new C++/CLI syntax was influenced by C#:

private:
   String^ lastname;
public:
   property String^ Lastname
   {
      String^ get()
      {
         return lastname;
      }
      void set(String^ value)
      {
         lastname = value;
      }
   }

C++/CLI has another syntax for properties where just the value is set and returned that doesn't need so much typing:

public:
   property String^ Firstname;

With the property keyword a property and a field is generated automatically. This style is very useful if there's no extra verification of the value with the set accessor, and the value returned is not calculated. Let's write smaller code :-)
The variable that's behind the property is generated automatically. There's no need to know the name of the generated variable because the compiler knows when to optimize the code to use the variable instead of the property.

Some time ago we had a discussion about properties and fields in C# - this issue can be solved with the C++/CLI syntax for properties.

Christian

Comments

 

jorgedbucaran@gmail.com said:

Thanks for the information, been looking for a while now. It is simple and works. By the way is there a way to "declare" the property in the header file but put the definition in the cpp file, I haven't been able to do so.

If you have the time please let me know.

January 18, 2008 11:23 PM
 

James Peckham said:

public:

  property String^ Lastname

  {

     String^ get();

     void set(String^ value);

  }

Namespace::Class::Lastname::set(String^ value)

     {

        lastname = value;

     }

Namespace::Class::Lastname::get()

     {

        return lastname;

     }

November 7, 2008 9:00 PM
 

Vic said:

Thanks!  That's exactly what I was looking for at the moment I found your answer above.

One little note:

The 'get' function definition requires a return type preceding the namespace, but otherwise, works like a champ!

June 11, 2009 2:30 PM

Leave a Comment

(required)  
(optional)
(required)  
Add