3

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?

Sajad Bahmani
  • 17,107
  • 27
  • 83
  • 107

5 Answers5

2

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#.

Glorfindel
  • 20,880
  • 13
  • 75
  • 99
Blindy
  • 60,429
  • 9
  • 84
  • 123
2

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.

Community
  • 1
  • 1
dirkgently
  • 104,737
  • 16
  • 128
  • 186
1

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
  • 47,396
  • 7
  • 93
  • 126
1

Python excels at this operation - here are bunch of examples: 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."

Community
  • 1
  • 1
GeePokey
  • 89
  • 4
0

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

Alex Reitbort
  • 13,315
  • 1
  • 38
  • 61
  • 1
    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 Aug 29 '10 at 18:35
  • Blindy is right: You can add methods to your own objects at runtime, but not other objects. – Gabe Aug 29 '10 at 18:55