views:

67

answers:

3

The simplest example would be the built in class keyValuePair(of T,U). I would like to be able to name the key property and value property differently depending on the usage and the designtime intellisense show me those names instead of key and value. Could this be done with reflection.Emit? Can it be done another way?

This seems like a small scope, and only saving perhaps 1 class of 8 lines of code, but it has broader implications for more complex classes.

As another example I'd like to be able to write new

Dim item as  KeyValuePair (of string, string)("LoanNumber", "LoanApplicationID")

or

KeyValuePair<string,string>("LoanNumber","LoanApplicationID") item;

and access in intellisense this type via:

var result=item.LoanNumber;

without having to create the following class in code every time I need a type with custom property names:

class LoanInfo
{
  string LoanNumber{get;set;}
  string LoanApplicationID{get;set;}
}

Don't get hung up on the use of keyValuePair, it was just for example since it functions close to what I want, but doesn't allow me to set the property names.

Is this possible?

A: 

No you can not. the reason is that it is dynamic and not only can't it work with intellisense it wil not compile since the property you try to reference doesn't exist.

I'd recommend creating it the way you don't want to : class LoanInfo{ string LoanNumber{get;set;} string LoanApplicationID{get;set;}}

I'd say you make that an interface which you can inherite the properties. but you still have to code the set and get.

greektreat
+1  A: 

You can use anonymous types this way. I know that VS2008/C# will understand the properties and give them to you with Intellisense and would assume it's the same way in VB, but I don't program in VB so YMMV.

Dim product = New With {Key .Name = "paperclips", .Price = 1.29}

Dim name as string 

name = product.Name

One of the most common places you see this used is in LINQ.

Dim namePriceQuery = From prod In products _
                     Select prod.Name, prod.Price

Dim firstName as string

firstName = namePriceQuery.First().Name
tvanfosson
I can't get Dim product = New With {Key .Name = "paperclips", .Price = 1.29}to compile in either language.
Maslow
Updated the syntax to VB. Not a VB guy (usually) and didn't realize that the var keyword (used in the OP) wasn't available there.
tvanfosson
Now if only we could get anonymous named types =)
Maslow
A: 

There isn't a way to do this currently, as there are no anonymous named types. However using DevExpress(coderush/refactor pro), you can create a sample anonymous type, and have it refactor that into a real class. I'm guessing resharper could do it also.

Maslow