NTDeveloper

In C#, one can retrieve metadata about a type by simply using the typeof(TYPE) construct. This is very useful. It would be equally useful to have a construct such as propertyof(TYPE, PROPERTY) that would return property information. Alas, no such operator exists. This omission has as an immediate consequence the inability of the developer to reference property names without typing in the literal name of the property in question. If the name of a property changes, one must remember to update all of the locations in source code where the name of the property is literally specified. Obviously, one can minimize the number of places that need to change by creating constants corresponding to the name of the property and the reference that constant whenever the name of the property is needed. This is not a great solution, but I can't think of anything better that isn't even more work. So, for example, I have a construct similar to the following:

Code Snippet

public class MyDomain

{

public class Person

{

public const string FirstName = "FirstName";

public const string LastName = "LastName";

//etc....

}

public class Address

{

public const string Street1 = "Street1";

public const string Street2 = "Street2";

//etc...

}

//etc...

}

Obviously, this is a PITA to create and maintain and it is easy to forget to update this code when a property on an object changes.

Has anyone devised a better system for referring to property names or comments on how the system described can be improved

Thank You



Re: Visual C# Language Approach to Referencing Property Names in Code

Greg Beech

What are you trying to achieve in referencing the properties by name rather than directly

Normally when there isn't the provision for something you're trying to achieve, it means there may be a better way of doing things that you haven't thought of yet.





Re: Visual C# Language Approach to Referencing Property Names in Code

NTDeveloper

There are any number of legitimate reasons why one would need to refer to the name of a property directly in code. For instance, if you implement the PropertyChanged event you will need the name of the property that changed in order to construct an instance of the PropertyChangedEventArgs class.

There are other examples that aren't quite as obvious. For example, suppose you have user interface elements that you want to associate with properties within an object model. One way to do this would be to attribute a UI element with the type of the object and the name of the property. You could achieve a similar result by creating a map in a static contructor that associates the two elements. In either case, you'll need the name of the property.

What I would like to achieve is compile-time checking of the property name in a manner similar to which the compiler verifies that the type X in the expression typeof(X) exists. Now, I don't believe that it's possible to achieve this within the current implementation of C#. The best that one could do would probably involve run-time checks via reflection, but even this requires quite a bit of work.

So...what's the next best thing





Re: Visual C# Language Approach to Referencing Property Names in Code

timvw

- Afaik there is no way to get method names at compile time...

- For INotifyPropertyChanged implementations you could request a StackTrace and get the previous frame... (But you'll have to make sure that no inlining occurs) (MetodImpl.NoInlining may help)

Code Snippet

public int X
{
set { this._x = value; this.RaisePropertyChanged(); }
}

protected void RaisePropertyChanged()
{
string propertyName = new StackTrace(false).GetFrame(1).GetMethod().Name.Substring(4));

...
}


- If you want to use methods as function parameters you're probably better of defining delegates.. This way you get type-safe (and compile time verification) of the functions that you're trying to use...





Re: Visual C# Language Approach to Referencing Property Names in Code

boban.s

In order to achieve to access property of a class using string, you will need to create string indexer of the class. I have write how to create string indexer here:
http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=963279&SiteID=1

But you mention the untyped problem when using strings. You can improve that if you put the property names strings in strings resource file.


and here http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=1132077&SiteID=1
In the second link, Enum is used to access properties, instead of strings like in first example. You will have enum value for every property.






Re: Visual C# Language Approach to Referencing Property Names in Code

Peter Ritchie

And what would you expect a propertyof(TYPE, PROPERTYNAME) keyword to do It sounds like you're looking for compile-time verification of a property to type. typeof(TYPE) is completely compile-time, it matches TYPE to the name of the time and gets the Type object for that type. You need that because there's no other way to get that information. If you were simply looking for a type that didn't exist you'd get a compile error. As such, something like propertyof(TYPE, PROPERTYNAME) requires that all that information exist before it compiles, in which case it's somewhat pointless.

Now, if you're looking for something at runtime, that's what reflection is for. You can easily query properties of a type or an object and runtime with methods like Type.GetProperties(). For example:

Code Snippet

foreach (PropertyInfo propertyInfo in typeof(Program).GetProperties())

{

if (propertyInfo.Name == "Count")

{

Console.WriteLine("Found");

}

}

Or

Code Snippet

foreach (PropertyInfo propertyInfo in form1.GetType().GetProperties())

{

if (propertyInfo.Name == "Count")

{

Console.WriteLine("Found");

}

}

Now, if you're looking to implement something like dynamic properties, that's entirely different and certainly not something a propertyof() keyword would be able to support.





Re: Visual C# Language Approach to Referencing Property Names in Code

NTDeveloper

Peter,

What I am suggesting is an operator that would work in a fashion completely analagous to typeof(), including compile-time verification.

For instance, if you have a type Person with a property called FirstName, you would be able to use propertyof() like this:

Code Snippet

PropertyInfo info = propertyof(Person, FirstName)

or

Code Snippet
PropertyInfo info = propertyof(Person.FirstName)

Thus, whenever you needed the name of the Person.FirstName property you could write

Code Snippet
string propName = propertyof(Person.FirstName).Name





Re: Visual C# Language Approach to Referencing Property Names in Code

NTDeveloper

That's an interesting approach and one which have used in the past; however, unfortunately, stack trace information is only available in DEBUG builds (or release builds with debug info)...




Re: Visual C# Language Approach to Referencing Property Names in Code

Peter Ritchie

NTDeveloper wrote:

Peter,

What I am suggesting is an operator that would work in a fashion completely analagous to typeof(), including compile-time verification.

For instance, if you have a type Person with a property called FirstName, you would be able to use propertyof() like this:

Code Snippet

PropertyInfo info = propertyof(Person, FirstName)

or

Code Snippet
PropertyInfo info = propertyof(Person.FirstName)

Thus, whenever you needed the name of the Person.FirstName property you could write

Code Snippet
string propName = propertyof(Person.FirstName).Name

Yes, but what is FirstName in your first example It can't exist on it's own currently in the language like Person can (as it's a type). The language can't syntactically check that line of code. If it could and Person didn't have a FirstName property it should cause a compile error (as does typeof(SomeNonExistentType)). Since you must have Person and FirstName correct, I don't see what the benefit is when you have reflection or can simply perform personObject.FirstName.

The second and third examples can currently be done through reflection. e.g.

Code Snippet

PropertyInfo propertyInfo = typeof(Person).GetProperty("FirstName");

...without having to expand the language to support this new type of type-less property identifer.

Again, if the end result of what you want to do is dynamic properties, a propertyof keyword isn't going to help you because it would be compile-time and dynamic properties would be a run-time.






Re: Visual C# Language Approach to Referencing Property Names in Code

Sean Fowler

NTDeveloper I think I know what you're getting at. I saw the need for this myself, and my Foundation product includes the generation of a enum for each class containing each of the properties. So you can do things like this:

Code Snippet

ITATQuery query = new ITATQuery();

query.AddWhere(Address.Properties.City, "London");

query.AddSelect(Address.Properties.AddressLine1);

query.AddSelect(Address.Properties.AddressLine2);

query.AddSelect(Address.Properties.PostalCode);

query.AddOrderBy(Address.Properties.PostalCode);

query.AddOrderBy(Address.Properties.AddressLine1, SortDirection.Desc);

query.SelectTop = 50;

query.SelectTopPercentWithTies = true;

query.Skip = 20;

AddressCollection addressList = Address.GetListByQuery(query);

These enums are used in many places. For example the validation returns a list of validation messages, which include the property enum that the message is about. And what if you want to get the original value of a property, or just see if it's changed The GetOriginalValue and IsChanged methods both take a property enum. I've also written a binding helper class which allows binding using the property enums rather than having to pass in the property name as a string.

There are plenty more places where these property enums are used, and I'm sure more will present themselves. So yes, I can certainly see your point.

Using enums is just a variation on your idea of using constants. It's worked very nicely, but of course it's a bit of a pain to maintain if you're not using code generation.

Sean






Re: Visual C# Language Approach to Referencing Property Names in Code

Mattias Sjogren

Peter Ritchie wrote:

The second and third examples can currently be done through reflection. e.g.

Code Snippet

PropertyInfo propertyInfo = typeof(Person).GetProperty("FirstName");

...without having to expand the language to support this new type of type-less property identifer.

Right, but there you have to specify the property name as a string. I think the whole point of having this operator would be to be able to just specify the identifier name as it is, and that way also get compile time checking that it exists.

When you have to manually write the name as a string, you always have a risk of typos, you lose IntelliSense, it may be missed by refactorings etc.

An operator like this has been discussed in the past (but often in a more general way, something like an infoof operator that would return whatever MemberInfo appropriate). And I think the C# team has confirmed that it would indeed be a useful thing to have.

Personally I'd settle for a way to just stringify an identifier name while still getting compile time checking that it's valid. Something like the # preprocessor operator in C++. It would be useful to prevent typos when throwing ArgumentExceptions and things like that.






Re: Visual C# Language Approach to Referencing Property Names in Code

Peter Ritchie

Mattias Sjogren wrote:

Right, but there you have to specify the property name as a string. I think the whole point of having this operator would be to be able to just specify the identifier name as it is, and that way also get compile time checking that it exists.

When you have to manually write the name as a string, you always have a risk of typos, you lose IntelliSense, it may be missed by refactorings etc.

An operator like this has been discussed in the past (but often in a more general way, something like an infoof operator that would return whatever MemberInfo appropriate). And I think the C# team has confirmed that it would indeed be a useful thing to have.

It's not that I don't see the value in getting member info for a property, I just don't see the value in getting that information for an arbitrary property name. like memberof(TypeName, PropertyName). The "PropertyName" aspect of that can't be an identifier, it needs some sort of scope. memberof(TypeName.PropertyName) would be doable, I think; as other's have discussed in other places. I doubt we'd see anything like that in a reasonable amount of time, if it hasn't already been shot down because of the introduction of a new keyword.