views:

126

answers:

5

I know in Ruby can add and modify method of class dynamically in run time. what about other language? what is C# ,can in this language modify or add some method and ... in run time and dynamically?

+2  A: 

Yes, in C# you can add methods at runtime through reflection and the Emitter object.

In C# 4.0 you can even do it in plain C# code with the Expando object. This is arguably closer to the Ruby way (it's practically a carbon copy if I remember correctly) and a lot easier to use.

Edit: All of this applies to all .NET languages, including VB.Net and F#.

Blindy
A: 

in C# 4 you have dynamic object which you can add/modify at run time.

Alex Reitbort
That's not entirely true, `dynamic` only means you can (try to) call whatever you want. Actually adding or removing methods is a different part of the DLR.
Blindy
Blindy is right: You can add methods to your own objects at runtime, but not other objects.
Gabe
+2  A: 

I think you are looking for prototype inheritance. A list of languages is mentioned in the same wikipedia page.

There is a similar question on SO which you can look up.

dirkgently
+1  A: 

The whole point of static type systems like C#'s is that all functionality defined for a particular type is known (and checked) at compile-time.

If you write

foo.jump(42);

the compiler verifies that whatever type foo has, it supports an operation called jump taking an integer parameter.

Recently, C# got the possibility of having dynamically checked objects through the dynamic type, which basically allows what you described in a very limited context, but nevertheless, the overall language is statically typed.

So what's left are dynamic languages like Ruby, where method existence is just checked at run-time (or call-time).

I think JavaScript can change so called prototypes to add methods to objects and basically achive the same thing as Ruby.

Dario
unless you define `foo` as `dynamic` in C# 4
M4N
@M4N: Yes. I consider this a corner case, but edited the answer nevertheless ;)
Dario
+1  A: 

Python excels at this operation - here are bunch of examples: http://stackoverflow.com/questions/962962/python-changing-methods-and-attributes-at-runtime

Lisp's object system is also quite dynamic: http://en.wikipedia.org/wiki/Common_Lisp_Object_System "CLOS is dynamic, meaning that not only the contents, but also the structure of its objects can be modified at runtime. CLOS supports changing class definitions on-the-fly (even when instances of the class in question already exist) as well as changing the class membership of a given instance through the change-class operator. CLOS also allows one to add, redefine and remove methods at runtime."

GeePokey
python can't modify the String class
rogerdpack