Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. .NET 2.0 features

.NET 2.0 features

Scheduled Pinned Locked Moved The Lounge
csharpc++comarchitecturequestion
43 Posts 17 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Marc Clifton

    J. Dunlap wrote:

    delegate co/contravariance

    What's that?

    J. Dunlap wrote:

    Marshal.GetDelegateForFunctionPointer(),

    When do you use that?

    J. Dunlap wrote:

    debugger visualizers

    Are these things you've written, or using the visualizers already in the debugger?

    J. Dunlap wrote:

    separate visibility levels for property accessors

    Ah, I forgot about that!

    J. Dunlap wrote:

    DynamicMethod

    Say, do you have those dynamic property setters folded into MyXaml yet? ;P Marc

    XPressTier

    Some people believe what the bible says. Literally. At least [with Wikipedia] you have the chance to correct the wiki -- Jörgen Sigvardsson
    People are just notoriously impossible. --DavidCrow
    There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer

    C Offline
    C Offline
    Christian Graus
    wrote on last edited by
    #24

    Marc Clifton wrote:

    Are these things you've written, or using the visualizers already in the debugger?

    Hah !!! The ones provided are useless. Why no bitmap visualiser ?

    Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

    1 Reply Last reply
    0
    • C Christian Graus

      I'm interested ( in light of the post below ) to know how many people have taken to the new 2.0 features ? We all use typed containers, I am sure, but how often do you use an anonymous method or iterators ? As I said on that thread, I used my first anonymous method, because it struck me as the ideal solution as I worked on it, before it's never seemed appropriate. I wonder if I'm just not in the habit yet, or this was truly the first time they were the right tool for the job. I love the idea of iterators, but I don't think I've used them in production code yet, and I imagine I need to look out for chances to change my mindset to be using them. How about you ?

      Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

      J Offline
      J Offline
      Judah Gabriel Himango
      wrote on last edited by
      #25

      CG, I have a huge library of classes that work on generic IEnumerable<T> and ICollection<T>; the whole library depends heavily on anonymous methods, in particular, Action<T> or Predicate<T> anonymous methods, and heavily relies on yield return iterators. Those things are so dang cool; the delayed execution opens up some interesting possibilities that didn't previously exist. I use the things for flattening hierarchies (yield returning the whole hierarchy recursively), returning an unknown set of results (say, any number matching some criteria specified by a Predicate<T> ), lots of cool stuff. :cool: So for me, of course generics is the great enabler and tops my usage list. Shortly after comes anonymous methods, then yield returns. All excellent features very useful in their current state. C# 3 builds heavily on these by introducing things like LINQ, lambda expressions, both of which use anonymous methods and yield returns under the hood.

      Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

      Last modified: Monday, August 14, 2006 9:39:31 PM --

      1 Reply Last reply
      0
      • J Jorgen Sigvardsson

        Still copy'n'paste in my book. :) List == IntList, List == StringList. Semantically, wherever you can put a List, you can put an IntList. The obvious benefit with the generics is that you don't have tio write all the methods (Append(), Delete(), etc) for each and every type you want to use. Ok, so I'll meet you halfway; it's copy'n'link for you, but copy'n'paste for the compiler/linker/JIT (it still has to "copy" for each new instantiation of the generic). :)

        -- [LIVE] From Omicron Persei 8

        J Offline
        J Offline
        Judah Gabriel Himango
        wrote on last edited by
        #26

        Jörgen Sigvardsson wrote:

        it still has to "copy" for each new instantiation of the generic

        Actually that's not true for .NET generics. For performance reasons, it will create a new instantiation for each value type (IntList, DoubleList, BoolList, etc) but for reference types (StringList, ObjectList, MyFooList) it uses only a single in-memory instantiation that works on reference types. :cool:

        Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

        J 2 Replies Last reply
        0
        • C Clickok

          My hopes in .Net 2.0 was Generics BUT... I wished create some type like MyBox Now I wish a collection of MyBox objects, but I can't. I can have only a collection of MyBox, MyBox, etc, but not of "MyBox" :doh: Another problem is the ?? operator and the Nullable notation (int?, string?, etc). How I can have problems using these together, I ever use Nullable instead... I will use iterators when I have nothing more important to do... The only thing what I use and abuse is the provider model (membership, sitemap, etc). But have the problem what is developed to read configurations of the web.config. If you wish use in Windows Forms, will be needed a lot of work to read from app.config (I have mentioned, what even if you use class libraries, you need referencing things like System.Web.Configuration, Syste.Web.Security, etc) This is my points and rants :) -- modified at 19:39 Monday 14th August, 2006 Jesus is Love! Tell to someone! :-)

          J Offline
          J Offline
          Judah Gabriel Himango
          wrote on last edited by
          #27

          click.ok wrote:

          Now I wish a collection of MyBox objects, but I can't.

          I agree with Jorgen, this really isn't an issue if you use generics/templates correctly IMO.

          click.ok wrote:

          Another problem is the ?? operator and the Nullable notation (int?, string?, etc). How I can have problems using these together, I ever use Nullable instead...

          I'm not sure what you're talking about. int? and double? is the same as Nullable<int> and Nullable<double>. You can use the ?? syntax on any nullable type, including Nullable and reference types.

          click.ok wrote:

          I will use iterators when I have nothing more important to do...

          Man, you're missing out my friend. :) yield return rocks, and allows one to achieve things previously very difficult to do. If you haven't checked them out, I'd love to show you some cool possibilities yield return opens up for you.

          Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

          Steve EcholsS 1 Reply Last reply
          0
          • C Christian Graus

            I'm interested ( in light of the post below ) to know how many people have taken to the new 2.0 features ? We all use typed containers, I am sure, but how often do you use an anonymous method or iterators ? As I said on that thread, I used my first anonymous method, because it struck me as the ideal solution as I worked on it, before it's never seemed appropriate. I wonder if I'm just not in the habit yet, or this was truly the first time they were the right tool for the job. I love the idea of iterators, but I don't think I've used them in production code yet, and I imagine I need to look out for chances to change my mindset to be using them. How about you ?

            Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

            S Offline
            S Offline
            Super Lloyd
            wrote on last edited by
            #28

            I think I use them all regularly. At least I'm using lots of: - generic (I had an unpleasant surprise a while ago: MyClass and MyClass have nothing in common! other than that they are cool). - anonymous delegate are great! (in fact I get used to the like of them in Java 2.0) - iterator. real cool once I understood I was not limited to GetEnumerator() but can be used to define all sorts of methods - myEvent += myMethod or myEvent += delegate(){..} (omitting the new EventHandler()) is great! - I use Nullable type quite less often, but they do come handy sometimes. And, most of all, I love the new Managed C++ 2.0, much less ambiguous and verbose than C++ cli 1.0 That's it... did I miss something? :~

            1 Reply Last reply
            0
            • J Jorgen Sigvardsson

              Marc Clifton wrote:

              As to iterators, I have yet to write my own iterator or type the word "yield". That's probably because of the nature of the code I write, rather than whatever kind of code you write that would leverage iterators.

              I haven't written a line of code using the yield stuff. But from what I can tell, it does have potential for clever patterns. Do you know if yield can handle non-linear collections such as dictionaries?

              -- Made From Meat By-Products

              J Offline
              J Offline
              Judah Gabriel Himango
              wrote on last edited by
              #29

              Jörgen Sigvardsson wrote:

              Do you know if yield can handle non-linear collections such as dictionaries?

              Yeah, you can iterate over any IEnumerable, including Dictionary<T>, and yield return anything you want from them. Iterators are actually very cool; they're somewhat a form of continuations the functional programming world knows well. Basically they let you return pieces of information on-demand rather than upfront: for example, you could yield return all even numbers. The beauty is that the code itself doesn't get executed until actually needed; so instead of waiting for a function to create a huge array containing all even numbers, consumers simply start iterating over your function's result and immediately get a result back. Each iteration will go to the next yield return; thus allowing all sorts of amazing possibilities previously unique to functional programming. IMO, iterators are a great feature in the language. Very cool stuff. :cool:

              Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

              Steve EcholsS 1 Reply Last reply
              0
              • M Marc Clifton

                Chris Maunder wrote:

                Nullable types

                Nullable types are utterly useless, IMHO, because they have no correspondence to DBNull.Value, which is what I care about. Marc

                XPressTier

                Some people believe what the bible says. Literally. At least [with Wikipedia] you have the chance to correct the wiki -- Jörgen Sigvardsson
                People are just notoriously impossible. --DavidCrow
                There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer

                J Offline
                J Offline
                Judah Gabriel Himango
                wrote on last edited by
                #30

                Marc Clifton wrote:

                Nullable types are utterly useless

                I've found some interesting uses for them. One recent thing I've been throwing around is lazy initialization of a value type. Say you've some integer that is only retrieved once, but that one-time retrieval requires a lot of work. So you get the value and store it later, right? Without nullables, you might do something like:

                bool hasRetrievedFoo;
                int foo;

                ...

                public int Foo
                {
                get
                {
                if(!hasRetrievedFoo)
                {
                this.foo = DoSomeWorkToGetFoo();
                this.hasRetrievedFoo = true;
                }
                return this.foo;
                }
                }

                It's not much, but with nullable we can eliminate the need for the boolean field.

                int? foo;
                ...
                public int Foo
                {
                get
                {
                if(foo == null)
                {
                foo = DoSomeWorkToGetFoo();
                }
                return foo.Value;
                }
                }

                The code is now more concise with fewer lines to accomplish the same task. Another thing I've found them useful for is in my data layer, calling stored procedures that take nullable parameters or returns nullable fields. Unfortunately you have to map DBNull to Nullable<T>, but that's better than the hack we used to have to do without nullables.

                Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                M 1 Reply Last reply
                0
                • J Judah Gabriel Himango

                  click.ok wrote:

                  Now I wish a collection of MyBox objects, but I can't.

                  I agree with Jorgen, this really isn't an issue if you use generics/templates correctly IMO.

                  click.ok wrote:

                  Another problem is the ?? operator and the Nullable notation (int?, string?, etc). How I can have problems using these together, I ever use Nullable instead...

                  I'm not sure what you're talking about. int? and double? is the same as Nullable<int> and Nullable<double>. You can use the ?? syntax on any nullable type, including Nullable and reference types.

                  click.ok wrote:

                  I will use iterators when I have nothing more important to do...

                  Man, you're missing out my friend. :) yield return rocks, and allows one to achieve things previously very difficult to do. If you haven't checked them out, I'd love to show you some cool possibilities yield return opens up for you.

                  Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                  Steve EcholsS Offline
                  Steve EcholsS Offline
                  Steve Echols
                  wrote on last edited by
                  #31

                  Judah Himango wrote:

                  yield return rocks, and allows one to achieve things previously very difficult to do. If you haven't checked them out, I'd love to show you some cool possibilities yield return opens up for you.

                  Excuse my ignorance, but what does "yield return" mean and why does it rock?


                  - S 50 cups of coffee and you know it's on!

                  • S
                    50 cups of coffee and you know it's on!
                    Code, follow, or get out of the way.
                  A 1 Reply Last reply
                  0
                  • J Judah Gabriel Himango

                    Jörgen Sigvardsson wrote:

                    Do you know if yield can handle non-linear collections such as dictionaries?

                    Yeah, you can iterate over any IEnumerable, including Dictionary<T>, and yield return anything you want from them. Iterators are actually very cool; they're somewhat a form of continuations the functional programming world knows well. Basically they let you return pieces of information on-demand rather than upfront: for example, you could yield return all even numbers. The beauty is that the code itself doesn't get executed until actually needed; so instead of waiting for a function to create a huge array containing all even numbers, consumers simply start iterating over your function's result and immediately get a result back. Each iteration will go to the next yield return; thus allowing all sorts of amazing possibilities previously unique to functional programming. IMO, iterators are a great feature in the language. Very cool stuff. :cool:

                    Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                    Steve EcholsS Offline
                    Steve EcholsS Offline
                    Steve Echols
                    wrote on last edited by
                    #32

                    Judah Himango wrote:

                    Basically they let you return pieces of information on-demand rather than upfront: for example, you could yield return all even numbers. The beauty is that the code itself doesn't get executed until actually needed; so instead of waiting for a function to create a huge array containing all even numbers, consumers simply start iterating over your function's result and immediately get a result back. Each iteration will go to the next yield return; thus allowing all sorts of amazing possibilities previously unique to functional programming.

                    Ah, I get it now, never mind - I should've read this whole post, before posting above. That does sound pretty cool. I can think of some date/time recurrency functions where this could be useful.


                    - S 50 cups of coffee and you know it's on!

                    • S
                      50 cups of coffee and you know it's on!
                      Code, follow, or get out of the way.
                    1 Reply Last reply
                    0
                    • Steve EcholsS Steve Echols

                      Judah Himango wrote:

                      yield return rocks, and allows one to achieve things previously very difficult to do. If you haven't checked them out, I'd love to show you some cool possibilities yield return opens up for you.

                      Excuse my ignorance, but what does "yield return" mean and why does it rock?


                      - S 50 cups of coffee and you know it's on!

                      A Offline
                      A Offline
                      AntonGogolev
                      wrote on last edited by
                      #33

                      Something like that: using System; using System.Collections.Generic; namespace ConsoleApplication1 { class Program { public static IEnumerable GetAllDivisibleBy(int denominator, int maximumValue) { for(int value = 1; value < maximumValue; ++value) if(value % denominator == 0) yield return value; } static void Main(string[] args) { foreach(int value in GetAllDivisibleBy(7, 61)) Console.WriteLine(value); } } } And the output is 7, 14, 21, and so forth. What is really interesting, is how it looks like in the compiled code (fire up Reflector and take a look). Here's an extract: [CompilerGenerated] private sealed class d__0 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { // Methods [DebuggerHidden] public d__0(int <>1__state); private bool MoveNext(); [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator(); [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator(); [DebuggerHidden] void IEnumerator.Reset(); void IDisposable.Dispose(); // Properties int IEnumerator.Current { [DebuggerHidden] get; } object IEnumerator.Current { [DebuggerHidden] get; } // Fields private int <>1__state; private int <>2__current; public int <>3__denominator; public int <>3__maximumValue; public int 5__1; public int denominator; public int maximumValue; }

                      1 Reply Last reply
                      0
                      • C Christian Graus

                        Chris Maunder wrote:

                        Nullable types? I want to since they match up with nullable fields in databases so nicely, but the effort involved in retrofitting what I currently have just makes me cringe. It'll happen next clean-up iteration, but not today.

                        Yeah, I use them a fair bit, for situations where my own code holds a number, but would otherwise need a 'magic' non-valid value like -1.

                        Chris Maunder wrote:

                        They let you get something done quickly and without needing to bother anyone else, but they just scream out "quick and dirty" to me. Give the code the respect of at least having a name and a place to live.

                        *grin* That's exactly how I've always felt, but like I said, this one time I realised they fit my need, because the code in the method where they are created has scope for the method, and the timer needed to find, remove and destroy a control that the calling method had created. So, it made my code a fair bit simpler. I've always thought iterators where the best of the new features, but, like you, I've not needed them yet, excepting for one time I needed a method to randomise a collection. I'm surprised that's not in there ( or is it ? )

                        Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

                        S Offline
                        S Offline
                        S Douglas
                        wrote on last edited by
                        #34

                        Christian Graus wrote:

                        Yeah, I use them a fair bit, for situations where my own code holds a number, but would otherwise need a 'magic' non-valid value like -1.

                        I was just beginning to wonder if I was on the wrong path. Gladly I can see I'm not the only one to initialize to an invalid number and check for that (not that I use any managed code).


                        I'd love to help, but unfortunatley I have prior commitments monitoring the length of my grass. :Andrew Bleakley:

                        1 Reply Last reply
                        0
                        • R RC_Sebastien_C

                          I like to know when the garbageman comes

                          J Offline
                          J Offline
                          Jorgen Sigvardsson
                          wrote on last edited by
                          #35

                          Better him than the postman (who always ring three times, when you're not at home!)

                          -- Behold, for I am THE CORRUPTOR!

                          R 1 Reply Last reply
                          0
                          • J Judah Gabriel Himango

                            Marc Clifton wrote:

                            Nullable types are utterly useless

                            I've found some interesting uses for them. One recent thing I've been throwing around is lazy initialization of a value type. Say you've some integer that is only retrieved once, but that one-time retrieval requires a lot of work. So you get the value and store it later, right? Without nullables, you might do something like:

                            bool hasRetrievedFoo;
                            int foo;

                            ...

                            public int Foo
                            {
                            get
                            {
                            if(!hasRetrievedFoo)
                            {
                            this.foo = DoSomeWorkToGetFoo();
                            this.hasRetrievedFoo = true;
                            }
                            return this.foo;
                            }
                            }

                            It's not much, but with nullable we can eliminate the need for the boolean field.

                            int? foo;
                            ...
                            public int Foo
                            {
                            get
                            {
                            if(foo == null)
                            {
                            foo = DoSomeWorkToGetFoo();
                            }
                            return foo.Value;
                            }
                            }

                            The code is now more concise with fewer lines to accomplish the same task. Another thing I've found them useful for is in my data layer, calling stored procedures that take nullable parameters or returns nullable fields. Unfortunately you have to map DBNull to Nullable<T>, but that's better than the hack we used to have to do without nullables.

                            Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                            M Offline
                            M Offline
                            Marc Clifton
                            wrote on last edited by
                            #36

                            Judah Himango wrote:

                            I've found some interesting uses for them.

                            Those are a couple good examples. Thanks! Marc

                            XPressTier

                            Some people believe what the bible says. Literally. At least [with Wikipedia] you have the chance to correct the wiki -- Jörgen Sigvardsson
                            People are just notoriously impossible. --DavidCrow
                            There's NO excuse for not commenting your code. -- John Simmons / outlaw programmer

                            1 Reply Last reply
                            0
                            • C Christian Graus

                              I'm interested ( in light of the post below ) to know how many people have taken to the new 2.0 features ? We all use typed containers, I am sure, but how often do you use an anonymous method or iterators ? As I said on that thread, I used my first anonymous method, because it struck me as the ideal solution as I worked on it, before it's never seemed appropriate. I wonder if I'm just not in the habit yet, or this was truly the first time they were the right tool for the job. I love the idea of iterators, but I don't think I've used them in production code yet, and I imagine I need to look out for chances to change my mindset to be using them. How about you ?

                              Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

                              M Offline
                              M Offline
                              Member 96
                              wrote on last edited by
                              #37

                              Just the new collection classes so far, but I went to 2 in the middle of a big project started in 1.1. For anything new I'll embrace as much of it as makes sense.

                              1 Reply Last reply
                              0
                              • J Jorgen Sigvardsson

                                Better him than the postman (who always ring three times, when you're not at home!)

                                -- Behold, for I am THE CORRUPTOR!

                                R Offline
                                R Offline
                                RC_Sebastien_C
                                wrote on last edited by
                                #38

                                no postman in my neighborhood, so no doorbell overuse :)

                                1 Reply Last reply
                                0
                                • J Judah Gabriel Himango

                                  Jörgen Sigvardsson wrote:

                                  it still has to "copy" for each new instantiation of the generic

                                  Actually that's not true for .NET generics. For performance reasons, it will create a new instantiation for each value type (IntList, DoubleList, BoolList, etc) but for reference types (StringList, ObjectList, MyFooList) it uses only a single in-memory instantiation that works on reference types. :cool:

                                  Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                                  J Offline
                                  J Offline
                                  Jorgen Sigvardsson
                                  wrote on last edited by
                                  #39

                                  Judah Himango wrote:

                                  it uses only a single in-memory instantiation that works on reference types. :cool:

                                  Ah, yes, the Object root. I keep forgetting about it. (Probably because I use C++ everyday :))

                                  -- If not entertaining, write your congressman

                                  1 Reply Last reply
                                  0
                                  • J Judah Gabriel Himango

                                    Jörgen Sigvardsson wrote:

                                    it still has to "copy" for each new instantiation of the generic

                                    Actually that's not true for .NET generics. For performance reasons, it will create a new instantiation for each value type (IntList, DoubleList, BoolList, etc) but for reference types (StringList, ObjectList, MyFooList) it uses only a single in-memory instantiation that works on reference types. :cool:

                                    Tech, life, family, faith: Give me a visit. I'm currently blogging about: And in this corner, the Party of Allah The apostle Paul, modernly speaking: Epistles of Paul Judah Himango

                                    J Offline
                                    J Offline
                                    Jorgen Sigvardsson
                                    wrote on last edited by
                                    #40

                                    Hmmmmm! Wait a minute. How can that work? Suppose I have this: (bear with me, I'm not fluent in generics syntax)

                                    template <typename T> class SomeClass {
                                    public void DoSomething(T obj) {
                                    obj.SomeMethod();
                                    }
                                    }

                                    class X {
                                    public void SomeMethod() { }
                                    }

                                    class Y {
                                    public void SomeMethod() { }
                                    }

                                    SomeClass<X> anObject = new SomeClass<X>();
                                    anObject.DoSomething(new X());
                                    SomeClass<Y> yetAnotherObject = new SomeClass<X>();
                                    anObject.DoSomething(new Y());

                                    Since classes X and Y are not directly related, how does SomeClass.DoSomething() call the correct method? Are method calls in MSIL made by method name lookup?

                                    -- This Episode Has Been Modified To Fit Your Primitive Screen

                                    J 1 Reply Last reply
                                    0
                                    • J Jorgen Sigvardsson

                                      Hmmmmm! Wait a minute. How can that work? Suppose I have this: (bear with me, I'm not fluent in generics syntax)

                                      template <typename T> class SomeClass {
                                      public void DoSomething(T obj) {
                                      obj.SomeMethod();
                                      }
                                      }

                                      class X {
                                      public void SomeMethod() { }
                                      }

                                      class Y {
                                      public void SomeMethod() { }
                                      }

                                      SomeClass<X> anObject = new SomeClass<X>();
                                      anObject.DoSomething(new X());
                                      SomeClass<Y> yetAnotherObject = new SomeClass<X>();
                                      anObject.DoSomething(new Y());

                                      Since classes X and Y are not directly related, how does SomeClass.DoSomething() call the correct method? Are method calls in MSIL made by method name lookup?

                                      -- This Episode Has Been Modified To Fit Your Primitive Screen

                                      J Offline
                                      J Offline
                                      Judah Gabriel Himango
                                      wrote on last edited by
                                      #41

                                      Jörgen Sigvardsson wrote:

                                      how does SomeClass.DoSomething() call the correct method? Are method calls in MSIL made by method name lookup?

                                      In short, in CLR generics, I can only put a SomeMethod call in there if T is guaranteed to have a SomeMethod() method. I can guarantee such by using interfaces (kind of like C++ pure abstract classes, except no implementation). This is a key difference between C++ templates and CLR generics; one reason why C++ templates are more powerful simply because they are a compile-time mechanism (which is fine, since C++ doesn't interop templates with other languages, since they get compiled down to real class instances with the real object in place of T), whereas CLR generics are more limiting because they are runtime-instantiated and are supported across disparate languages; they don't get compiled down to new SomeClass instances, with your type replacing T. Such deep runtime support of generics has some benefits: - we can do things like expose generic instances, say a List<int> to all other .NET assemblies, be they C#, VB.NET, IronPython, C++/CLI, etc. - we can use reflection to investigate, at runtime, the type of a List<T> instance and it will correctly give back a List<int> type in this case. This is something Java's generics fail to do, since Java generics are entirely syntax candy, no runtime support. But putting generics in the runtime also has some limitations: In C++, if there isn't SomeMethod on the template instance you've instantiated, you get a compile-time error. But for CLR generics, the compiler simply will not let you put in a method call into a generic class if the type doesn't support that method. And since the generic class type is, by default, System.Object as you mentioned, there is no SomeMethod on System.Object. To get around this, the CLR has what's called a constraint. You can constrain the T in the generic class to any object that supports some interface, that inherits from some type, or has a default constructor, or is a value type, and so on. Lots of constraint possibilities. If I wanted to achieve what you posted in the above C++ code, you'd do it like this:

                                      interface ISomeMethod
                                      {
                                      void DoSomething();
                                      }

                                      class SomeClass<T>
                                      where T : ISomeMethod // Only allow this generics class to be used with an object that implements the ISomeMethod interface.
                                      {
                                      void DoSomething(T obj)
                                      {
                                      obj.DoSomething(); // this works, because of the constraint

                                      J 1 Reply Last reply
                                      0
                                      • C Christian Graus

                                        I'm interested ( in light of the post below ) to know how many people have taken to the new 2.0 features ? We all use typed containers, I am sure, but how often do you use an anonymous method or iterators ? As I said on that thread, I used my first anonymous method, because it struck me as the ideal solution as I worked on it, before it's never seemed appropriate. I wonder if I'm just not in the habit yet, or this was truly the first time they were the right tool for the job. I love the idea of iterators, but I don't think I've used them in production code yet, and I imagine I need to look out for chances to change my mindset to be using them. How about you ?

                                        Christian Graus - Microsoft MVP - C++ Metal Musings - Rex and my new metal blog

                                        S Offline
                                        S Offline
                                        Stuart Dootson
                                        wrote on last edited by
                                        #42

                                        Well - I don't use .NET, I use C++ with Boost[^], but I make use of the Boost equivalents of iterators[^] and anonymous functions[^]. Iterators are for anything that has a concept of enumerability (mostly files of wacky formats for me). As an example - I have an application where I have to read a big-endian file. So, I wrap up a file iterator and a byte reverser together and I get an iterator that gives me little endian results (joy!). I use anonymous methods pretty much wherever I use Standard Template Library algorithms. Also, in conjunction with generic function objects[^] - customising some functionality by passing in an adapted function.

                                        1 Reply Last reply
                                        0
                                        • J Judah Gabriel Himango

                                          Jörgen Sigvardsson wrote:

                                          how does SomeClass.DoSomething() call the correct method? Are method calls in MSIL made by method name lookup?

                                          In short, in CLR generics, I can only put a SomeMethod call in there if T is guaranteed to have a SomeMethod() method. I can guarantee such by using interfaces (kind of like C++ pure abstract classes, except no implementation). This is a key difference between C++ templates and CLR generics; one reason why C++ templates are more powerful simply because they are a compile-time mechanism (which is fine, since C++ doesn't interop templates with other languages, since they get compiled down to real class instances with the real object in place of T), whereas CLR generics are more limiting because they are runtime-instantiated and are supported across disparate languages; they don't get compiled down to new SomeClass instances, with your type replacing T. Such deep runtime support of generics has some benefits: - we can do things like expose generic instances, say a List<int> to all other .NET assemblies, be they C#, VB.NET, IronPython, C++/CLI, etc. - we can use reflection to investigate, at runtime, the type of a List<T> instance and it will correctly give back a List<int> type in this case. This is something Java's generics fail to do, since Java generics are entirely syntax candy, no runtime support. But putting generics in the runtime also has some limitations: In C++, if there isn't SomeMethod on the template instance you've instantiated, you get a compile-time error. But for CLR generics, the compiler simply will not let you put in a method call into a generic class if the type doesn't support that method. And since the generic class type is, by default, System.Object as you mentioned, there is no SomeMethod on System.Object. To get around this, the CLR has what's called a constraint. You can constrain the T in the generic class to any object that supports some interface, that inherits from some type, or has a default constructor, or is a value type, and so on. Lots of constraint possibilities. If I wanted to achieve what you posted in the above C++ code, you'd do it like this:

                                          interface ISomeMethod
                                          {
                                          void DoSomething();
                                          }

                                          class SomeClass<T>
                                          where T : ISomeMethod // Only allow this generics class to be used with an object that implements the ISomeMethod interface.
                                          {
                                          void DoSomething(T obj)
                                          {
                                          obj.DoSomething(); // this works, because of the constraint

                                          J Offline
                                          J Offline
                                          Jorgen Sigvardsson
                                          wrote on last edited by
                                          #43

                                          Thanks for the clarification! Much obliged. :)

                                          -- Touch eyeballs to screen for cheap laser surgery

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups