Friday, March 2, 2007

Symbols in C# 3.0

One of the languages that gets a lot of buzz nowadays is Ruby. Ruby is a dynamic, object-oriented language with a flexible syntax. The language allows you to change an object's structure at run-time by adding new methods. You can also create entirely new code by building a code string and executing it with the eval function.

i = 30
eval("i = 20")


This function alone, which is shared by Python and Javascript, is enough to enable all sorts of advanced metaprogramming. However Ruby has something that the aforementioned languages don't have: symbols. Symbols are just strings that the interpreter checks to ensure they are valid identifier names. This just means that Ruby will throw an error if you attempt to use a symbol that contains spaces, starts with a digit, or is otherwise invalid as an identifier. This is the only method Ruby provides to manipulate code as data. In the words of jazz singer Peggy Lee: "Is that all there is?" Yup.

Despite the simplicity of this feature symbols are still incrementally more useful than strings when combined with metaprogramming techniques like code generation. Typically a method is created which takes an array of symbols and generates code for each of them using eval. The advantage of using a symbol instead of a string is that your generated code is more likely to be syntactically correct.

In the following Ruby example two functions attr_reader and attr_writer are passed an array of symbols and then create accessor and mutator methods for the name, author, and duration fields in the Song class. This is equivalent to creating three properties in .NET.

class Song
attr_reader :name, :artist, :duration
attr_writer :nmae, :artist, :duration
end


Notice the ":" before each argument. That is how you create a symbol in Ruby. The observant reader will notice that in the second function I've made a typo writing ":nmae" instead of ":name". This was intentional because I wanted to point out an important fact that might not be immediately obvious. Specifically that symbols don't necessarily refer to an identifier that exists at compile-time. In fact, there is no compile-time in Ruby. It is an interpreted language. As a result the code above will not trigger an error. Remember: symbols are just strings.

When working in a statically-typed language like C# I find having to put code in a string very annoying because my IDE is powerless to point out typos like the one above. Also, my IDE cannot provide me with intellisense or rename an identifier globally for me. However certain important interfaces in the .NET framework require me to put code into strings. Consider this Customer class that implements the System.ComponentModel.INotifyPropertyChanged interface, enabling it to be data-bound to WinForms controls:

public class Customer : INotifyPropertyChanged {

private string name;
public string Name {


get { return name; }

set {
name = value;
OnPropertyChanged(this, new PropertyChangedEventArgs("Name")); // notice we have to put our property symbol in a string
}

}
protected void OnPropertyChanged(object source, PropertyChangedEventArgs args)

{

if (this.PropertyChanged != null)
this.PropertyChanged(source, args);

}

public event PropertyChangedEventHandler PropertyChanged;

}



In this case it would be really nice to have a symbol-like construct in C#, preferably one checked for correctness by the compiler. Thankfully in C# 3.0 writing a function that will return the string representation of a symbol is trivial. You can replace the applicable line above with:

OnPropertyChanged(this, new PropertyChangedEventArgs (this.GetPropertySymbol(o => o.Name)));

This is just beautiful. Intellisense even kicks in as we type the expression:



Even if we somehow manage to make a typo with intellisense helping us, the program will not even compile. Also we can now do a global rename of the property using refactoring tools.

How does it work? GetPropertySymbol is an extension method that takes an expression tree as its argument. I've blogged about expression trees extensively here and here so I'll assume you know all about them. You do read my blog religously don't you ;-)

Did you notice that we didn't have to specify any type information and yet intellisense still managed to display the list of Customer members? This works because GetPropertySymbol declares that the first argument to the lambda function it is passed is the same type that the extension method is applied to. As a result C# can figure out the type with type inference!! Without further ado, here is the single line function definition:



All I'm doing is grabbing the member expression inside the lambda expression body and returning the name! This function comes in handy when doing data-binding as well:

this.DataBindings.Add (
new Binding(
this.GetPropertySymbol(o => o.Text),
this,
this.GetPropertySymbol(o => o.GameTitle)
)
);

Incidentally I hope no one gets the impression that I'm putting Ruby down. In fact, I really like Ruby. However the most interesting thing to me about the language is not it's oft-touted metaprogramming capabilities but the way it encourages you to write code in continuation-passing style (CPS). This approach can make writing certain types of client-server applications like web applications much more simple conceptually. I advise you to check the language out. Learning programming languages which approach problems in radically different ways than the ones you are used to will definitely make you a better programmer.

50 comments:

Judah Himango said...

Very, very cool. I hate having to put code in between strings; refactors break it. We have to do this often in unit tests as well as data layer programming...if symbols could replace this, it would be absolutely brilliant.

I've submitted this article to dotnetkicks.com

Jafar Husain said...

Can you give me an example of how you would use symbols in unit tests? I'm curious because I never found the need.

Thanks

Darius Damalakas said...

Correct me if i understood wrong, but:
is there a way to write
student => LastContract => DateCrated?

I.e. to get the property name via property path?
Student.LastContract.DateCreated?

Jafar Husain said...

The current version doesn't work for nested member expressions. It's trivial to modify it to do so though. Just keep following up the MemberExpressions up the expression tree and appending the names to a string. Then you would be able to do:

this.GetPropertySymbol( o => o.Student.LastContact.DateCreated )
//returns "Student.LastContact.DateCreated"

If you have any questions or problems doing it yourself I'll write the code and post it.

Jafar Husain said...

Oh the heck with it. I just wrote the code and posted it :-). Check it out here.

Judah Himango said...

In unit tests, we'll do things like this in mock objects:

// myFooMock is a mock IFoo, which has a Fobnicate method
myFooMock.Expect("Fobnicate");

If I'm understanding you right, we should be able to use symbols to get the name of the Fobnicate method. Is that accurate, Jafar?

kfarmer said...

Actually, if you back your code up just one step, you've got the basics of the "info-of" feature-wish: a way to get MemberInfo without having to jump through all the hoops.

Nice example, by the way.

John Rusk said...

Judah,

The case you mention (symbol for method can be fully implemented right now in C# 2.

See http://dotnet.agilekiwi.com/blog/2007/04/symbols-part-2.html

John Rusk said...

Oopps, that URL didn't come through. I'll try again:

Anonymous said...

Here's another idea: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1487253&SiteID=1&mode=1

which is a refinement of yours (requires hypothetical compiler change though)

Anonymous said...

@Dariusyou are getting "=>" wrong, it is c#'s lambda/anonymous function

In c#: (o => o.Name)
In python: (lambda(o): o.Name)
In javascript: (function(o){return o.Name;})
In (my broken understanding of) ruby: {|o| return o.Name}
#or probably just
{|o| o.Name}


to get what you want do: ( student => student.LastContract.DateCreated)

Your exapmle will return a function that takes an object as parameter and returns another function that takes anothey object as parameter, then returns the value of "DateCreated" in the closure

Judah Himango said...

Jafar, I'm aware one can do it with methods right now in C# 2: simply construct a delegate around your function, then call the Name property on the delegate target. But you can't do it with properties, since delegates can't point to properties.

So, I'm looking forward to symbols like this in C# 3. :)

OnlinePharmacy said...
This comment has been removed by a blog administrator.
viagra adverse reactions said...

bDuek2 Thanks to author.

order meridia cheap said...

Nice Article.

cheaper in motel panama repub said...

Thanks to author.

name said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

blue collar comedy tour bit downloads said...

Magnific!

all earth eco tours llc said...

actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

fairmont specialty insuran said...

Thanks to author.

ringtones said...

Please write anything else!

said...

Nice Article.

fioricet said...

AIXweu actually, that's brilliant. Thank you. I'm going to pass that on to a couple of people.

how to download free rin said...

Hello all!

Scott Hagie said...

Interestingly enough, the equivalent VB syntax doesn't work with intellisense:


Public Module SymbolExtensions
<Extension()> _
Public Function GetPropertySymbol(Of T, R)(ByVal obj As T, ByVal expr As Expression(Of Func(Of T, R))) As String
Return CType(CType(expr, System.Linq.Expressions.LambdaExpression).Body, System.Linq.Expressions.MemberExpression).Member.Name
End Function
End Module

Me.GetPropertySymbol(Function(o) o.Name)

But, the compiler does catch it, so that's something.

Anonymous said...

My friends and I like to buy Anarchy credits, because the Anarchy Online credits is very useful to upgrade equipment. Only your equipment becomes better, then you can win this game. In Anarchy gold, you can buy everything you want in this game. Tomorrow will be my birthday, so my friends promise to buy AO credits as gifts. I am so happy. They understand me so well, Anarchy online gold is my favorite.

I like angels gold very much because it is very useful. In fact at first sight I have fallen in love with angels online gold. So no matter how much I have spent to buy angels gold, I never regret. Because of cheap angels online gold, I meet a lot of friends.

Anonymous said...

aion chinaaion china gold,
aion cn goldaion chinese gold,
aion gold chinaaion gold chinese,
china aion goldchinese aion gold,
aion china kinaaion chinese kina,
aion kina chinachina aion kina,
aion china buybuy aion china,
aion chinese server goldaion cn server gold,
aion china server goldchina aion server gold,
chinese aion server goldaion chinese server gold,
aion cn server kinaaion china server kina,
china aion server kinachinese aion server kina

buy runescape said...

Now do you worried about that in the game do not had enough wakfu kamas to play the game, now you can not worried, my friend told me a website, in here you can buy a lot wakfu gold and only spend a little money, do not hesitate, it was really, in here we had much wakfu money, we can sure that you will get the wakfu kama, quick to come here to buy wakfu kamas.

Now do you worried about that in the game do not had enough runescape gold to play the game, now you can not worried, my friend told me a website, in here you can buy a lot rs gold and only spend a little money, do not hesitate, it was really, in here we had much runescape money, we can sure that you will get the cheap rs gold, quick to come here to buy runescape.

Affordable Luxurious Wedding Dress Blog said...

cheap wedding gowns,
discount bridal gowns,
China wedding dresses,
discount designer wedding dresses,
China wedding online store,
plus size wedding dresses,
cheap informal wedding dresses,
junior bridesmaid dresses,
cheap bridesmaid dresses,
maternity bridesmaid dresses,
discount flower girl gowns,
cheap prom dresses,
party dresses,
evening dresses,
mother of the bride dresses,
special occasion dresses,
cheap quinceanera dresses,
hot red wedding dresses

srggy said...

new polos men poloswomen polosdiscount polos
summer polospolo shirts whosalepolo fashionembroodered polos
tennis racketsclothing poloclothingedhardyshirt
edhardyclothingsummer ed hardy clothingcheap shirtsed hardy brand
cheap ed hardypolo shirts cheapcheap tennis racketsdiscount tennis rackets
ralphlaurenpoloshirtscheappolospolo fashionpolo logo
polo shirts in voguepolo women clothinged-hardy shirtsed-hardy sunglasses
ed-hardy logopolofashioncheaptennisracquetsed-hardy sunglasses
ed-hardy sunglassesed-hardy clothingdiscount polo shirtswholesale ed hardhy shirts
clothingfashionpolos summertennisrackets discountpolos clothes
wilson k sixedhardyclotheswholesale-polo-shirts

srggy said...

Andy Roddick's signature babolat pure drive, Pure Drive Roddick Babolat wilson k six, features GT Technology combined with head microgel and prince-o3-tour, versatile and accurate cheap tennis racquets with unparalleled performance and incredible feel with less vibrations.

srggy said...

Look !The shirt for men's clothing,ed hardy clothing, The ed hardy clothes on each piece were created ed hardy shirts and is recognized globally for his technical brilliance and mesmerizing imagery.Short sleeves ed hardy mens and ed hardy womens , remember to check out ed hardy t-shirts because they are very popular in demand too!Combination with ed hardy sunglasses,very handsome.

crat said...

The button to break the conventional design of polo shirts, the depth of clear lines of wholesale polo shirts from the Department of V on the first gives the impression of a unique, tailor-made with dark-green Lacoste polo shirts with the color scheme of Red and the casual cheap lacoste polos, stressed a summer of non-traditional use of color, so that the overall shape ofralph lauren polo shirts is full of flavor. The classic black-and-white cheap ralph lauren polos with matching black-and-white striped discount ralph lauren polos elegant leaves the impression that the import of polo clothing and black shoes brighten even more people.

Anonymous said...

polo ralph lauren integrates two types of luxury and leisure style, now more and more popular men’s “thin” burberry polos, most designers have sought to perfect the cut with “cutting” a bag of bones of the body ralph lauren polo shirts. It is amazing that a tight lacoste polo shirts with pencil pants, full of retro style with a European aristocratic culture of leisure cheappolos.

j said...

http://2009tennis.blogspot.com/
http://www.free-blog-site.com/tennis
http://o3.indiatimes.com/racquet/
http://cid-8c8a918b06ff68fd.spaces.live.com/?lc=2052
http://2009tennis.cocolog-nifty.com/
http://2009tennis.blog.drecom.jp/
http://2009tennis.blog.shinobi.jp/
http://www.actiblog.com/slary/
http://pshirts.blog126.fc2.com/
http://www.free-blog-site.com/shirts
http://nikepuma.blog.shinobi.jp/
http://hardy55.blog126.fc2.com/
http://cid-f80137f6d1a8020b.spaces.live.com/?lc=2052
http://www2.atword.jp/sdgdyhd/
http://kurumaro.com/hardy/
http://hardyclothes.jugem.jp/
http://www.actiblog.com/sfawagfra/
http://thediary.org/cheaphandbags/
http://ameblo.jp/kaowy/
http://sale.edublogs.org/
http://www2.atword.jp/jak/
http://09handbags.blog126.fc2.com/
http://sun15.cocolog-nifty.com/
http://ameblo.jp/ailsa15/
http://junior2tennis.blog.shinobi.jp/

j said...

In preparation for the purchase of a tennis racquetbefore, we must consider your financial ability to bear; On this basis, a further comparison, as far as possible, choose your tennis racket. Now a lot of cheap tennis racquet and more mixed materials, the proportion of mixed-use to control the stiffness of the tennis racquet discount and the shock-absorbing capacity, the more rigid cheap tennis racket, the swing more powerful force; but the relative resilience of the shock-absorbing capacity and discount tennis racket performance of talks on the easier it is for the wrist and elbow injury.
head junior tennis racket
wilson tennis racquet
wilson tennis racket
head tennis racket
babolat tennis racket
Womens Handbags
Cheap Purses
Designer Handbags

j said...

Burberry polo shirt the steady, solid, so many young girls also love it. Speaking of people of a ralph lauren polo, think it a sign of nobility elegant waving in the horse club.spyder jacket in the cold in your winter activities can be easily.columbia jacket it is expensive, but here you do not need to consider the price of it. the north face jacket one of my favorite money, I do not know how many in this world of its fans.
ed hardy clothing
ed hardy clothes
ed hardy shirts
ed hardy t-shirts
ed hardy sunglasses
ed hardy mens
ed hardy womens
Wholesale Handbags
Cheap Handbags

asdfsadf said...

nike shoes, jordan shoes, nike dunks, nike air force 1, nike shox, nike shoes, nike shox, nike dunks, nike air force 1, nike shox, nike shoes, nike shox oz, nike shox nz, nike shox r3, nike shox r4, nike shox r5, nike shox tl
nike air force 1










nike Air Force 1, nike shoes, Jordan shoes, nike sb dunks, cheap nike Air Force 1, cheap nike shoes, cheap Jordan shoes, cheap nike sb dunks, discount nike Air Force 1, discount nike shoes, discount Jordan shoes, discount nike sb dunks, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes












nike shoes, nike shox, jordan shoes, puma shoes, nike dunks, nike air max, nike air force one, timberland boots, ugg boots, nike shoes, nike shox, nike air force 1, nike sb dunks, puma shoes, nike air max, jordan shoes, ugg boot, jordan sneakers, timberland shoes, bape shoes, nike shoes, nike shox, nike dunks, nike air force 1, jordan shoes

huyuni said...

if you or your friend want to China Wholesaleplease cheack you can buy buy products wholesale here from wholesale from china ,the China Wholesalers on China Wholesale wholesale from china buy products wholesale China Wholesalers

huyuni said...

quelle chaussures pumapaire de chaussures pour hommes choisir?!? La réponse est toute simple:chaussures nike une paire de baskets en partie vernies. du 17ème au 5ème rang, qui lui offre une place dans un top 5 largement tn requindominé par les sites de vente de produits high-tech. Le site de réservation d'hôtels Bookings.com gagne pour sa part 47 places et atteint le 8ème rang.

huyuni said...

Charlestoncheap columbia jackets. turned a pair of double plays to do the trick. spyder jacketsThe had at least one runner on in every inning but the first and outhit the RiverDogs by a 12-6 margin Lawal should be a focal point of the Yellow cheap polo shirts along with highly touted newcomer, 6-9 Derrick Favors, rated as the No. 1 power forward on the ESPNU 100. The Yellow Jackets

huyuni said...

Cheap Brand Jeans ShopMen Jeans - True Religion Jeans, burberry polo shirtsGUCCI Jeans, Levi's Jeans, D&G Jeans, RED MONKEY Jeans, Cheap JeansArmani Jeans, Diesel Jeans, Ed hardy Jeans, Evisu Jeans, Women JeansJack&Jones Jeans...Lacoste Polo Shirts, , Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price. clothingol.com offers lot of 10 lacoste polo shirts and lot of 20 cheap polo shirts. clothingol.com offers classic fit polo shirts. polo clothing

huyuni said...

nike shoes & Puma Shoes Online- tn nike,puma shoes,puma cat, baskets cheap nike shox, air max.cheap nike shox r4 torch, cheap nike air, nike running shoes air max, puma speed and more. Paypal payment.nike running shoes Enjoy your shopping experience on Nike & Puma Shoes Online Store.

nike said...

http://www.shoesbuying.com/nike-shox-shoes-mens-shox-c-163_127.htm : men's shox R4
http://www.shoesbuying.com/nike-shox-shoes-womens-shox-c-163_128.htm : women's shox R4
http://www.shoesbuying.com/nike-shox-shoes-c-164.htm : nike shox R5
http://www.shoesbuying.com/nike-shox-shoes-mens-shox-c-164_144.htm : nike shox
http://www.shoesbuying.com/nike-shox-shoes-womens-shox-c-164_145.htm : womens shox
http://www.shoesbuying.com/nike-shox-c-165.htm : nike shox
http://www.shoesbuying.com/nike-shox-mens-shox-c-165_129.htm : nike shox
http://www.shoesbuying.com/nike-shox-womens-shox-c-165_130.htm : womens shox
http://www.shoesbuying.com/nike-shox-c-171.htm : nike tl3
http://www.shoesbuying.com/nike-shox-mens-shox-c-171_172.htm : mens nike tl3
http://www.shoesbuying.com/nike-shox-womens-shox-c-171_173.htm : women's tl3
http://www.shoesbuying.com/nike-trainers-lovers-c-118.htm : nike trainers
http://www.shoesbuying.com/other-nike-shoes-c-193.htm : nike shoes
http://www.polosales.com/ : cheap polo shirts
http://www.polosales.com/ : polo shirt
http://www.polosales.com/ : lacoste polo shirts
http://www.polosales.com/ : ralph lauren polo shirts
http://www.polosales.com/ : wholesale polo shirts
http://www.superpolos.com/mens-lacoste-solid-classicfit-polo-shirt-light-yellow-p-146/ : Yellow Polo Shirt
http://www.superpolos.com/wholesale-mens-short-sleeve-lacoste-polo-shirts-p-132/ : Men's Polo Shirts
http://www.superpolos.com/wholesale-mens-short-sleeve-lacoste-polo-shirts-p-133/ : Wholesale Polo Shirts
http://www.superpolos.com/ : polo shirts
http://www.superpolos.com/ : Lacoste polo shirts
http://www.pumachaussure.com/ : chaussure puma
http://www.pumachaussure.com/ : chaussures puma

Anonymous said...

Acer Laptop Batteries
Apple Laptop Batteries
Compaq Laptop Batteries
Dell Laptop Batteries
HP Laptop Batteries
IBM Laptop Batteries
Lenovo Laptop Batteries
Samsung Laptop Batteries
Sony Laptop Batteries
Toshiba Laptop Batteries
ASUS Laptop Batteries
Gateway Laptop Batteries
LG Laptop Batteries
NEC Laptop Batteries
HITACHI Laptop Batteries
Panasonic Laptop Batteries
BenQ Laptop Batteries
Fujitsu Laptop Batteries

琪琪 said...

who has started the last 12 games in the absence of Yi Jianlian. "I know I've improved a ton defensively this season."
...................................................
.......

琪琪 said...

you are not our mother. She has a soft, pleasant voice, but your voice is rough, you are the wolf.
...................................................
......

琪琪 said...

If on the other hand, you need a detailed manual, the instructions are there for you to access.
...........................................................
...

Anonymous said...

情趣用品|情趣用品|情趣用品|情趣|情趣用品|情趣

eda said...

情趣按摩棒,自慰套,角色扮演,按摩棒,跳蛋,跳蛋,
情趣,情趣,角色扮演服,吊帶襪,丁字褲,情趣用品,情趣用品,跳蛋,男女,
潤滑液,SM,情趣內衣,內衣,性感內衣,自慰器,充氣娃娃,AV,
按摩棒,電動按摩棒,飛機杯,視訊,自慰套,自慰套,

About Me

My Photo
I'm a software developer who started programming at age 16 and never saw any reason to stop. I'm working on the Presentation Platform Controls team at Microsoft. My primary interests are functional programming, and Rich Internet Applications.