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. General Programming
  3. C#
  4. Help with generics [modified]

Help with generics [modified]

Scheduled Pinned Locked Moved C#
tutorialcsharphtmlcomdata-structures
8 Posts 3 Posters 1 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.
  • G Offline
    G Offline
    GuimaSun
    wrote on last edited by
    #1

    Hello, I'm trying to access an element from the following function, can you help me ? I've tried a lot of constructions without success. Edit: I`m using VS2008\.NET 3.5 The function below should access the "i" value for single types and arrays at the same time, for single types it`s ok, but for arrays I don`t know how to access array elements. I can check i.GetType().IsArray, but don`t know how to access particular elements. static void function(ref T i) { string s; if ( !i.GetType().IsArray ) s = i.ToString(); // ok else // next line doesn't compile: Cannot apply indexing with [] to an expression of type 'T' int a = i[0]; } Caller code example: int a = 5; function(ref a); int[] arri = { 3, 5, 7 }; function(ref arri); Thanks for any help.

    GuimaSun www.nexsun.com.br NEXSUN TechZone

    0 T 2 Replies Last reply
    0
    • G GuimaSun

      Hello, I'm trying to access an element from the following function, can you help me ? I've tried a lot of constructions without success. Edit: I`m using VS2008\.NET 3.5 The function below should access the "i" value for single types and arrays at the same time, for single types it`s ok, but for arrays I don`t know how to access array elements. I can check i.GetType().IsArray, but don`t know how to access particular elements. static void function(ref T i) { string s; if ( !i.GetType().IsArray ) s = i.ToString(); // ok else // next line doesn't compile: Cannot apply indexing with [] to an expression of type 'T' int a = i[0]; } Caller code example: int a = 5; function(ref a); int[] arri = { 3, 5, 7 }; function(ref arri); Thanks for any help.

      GuimaSun www.nexsun.com.br NEXSUN TechZone

      0 Offline
      0 Offline
      0x3c0
      wrote on last edited by
      #2

      static void function(ref T[] i)

      Your code declares i as a T. In order to access it as an array, you need to specify it as one (unless you like pointer arithmetic and a whole world of pain). But your function code is concerning. The idea of generics is to make something type-safe. What happens if T is a String? A nasty error. Incidentally, you should have gotten another error at the invocation point (something like "Cannot implicitly convert between int[] and int")

      1 Reply Last reply
      0
      • G GuimaSun

        Hello, I'm trying to access an element from the following function, can you help me ? I've tried a lot of constructions without success. Edit: I`m using VS2008\.NET 3.5 The function below should access the "i" value for single types and arrays at the same time, for single types it`s ok, but for arrays I don`t know how to access array elements. I can check i.GetType().IsArray, but don`t know how to access particular elements. static void function(ref T i) { string s; if ( !i.GetType().IsArray ) s = i.ToString(); // ok else // next line doesn't compile: Cannot apply indexing with [] to an expression of type 'T' int a = i[0]; } Caller code example: int a = 5; function(ref a); int[] arri = { 3, 5, 7 }; function(ref arri); Thanks for any help.

        GuimaSun www.nexsun.com.br NEXSUN TechZone

        T Offline
        T Offline
        Thomas Weller 0
        wrote on last edited by
        #3

        You have to declare the argument as an array if it is one. Like so:

        static void function(ref T[] i)

        But your next line:

        int a = i[0];

        won't compile anyway, since the compiler cannot garantuee that T is of a type that is convertible to an int. Use something like this instead:

        static void function(ref T[] i) where T : struct
        {
        try
        {
        int a = Convert.ToInt(i[0]);

            // your code goes here
        }
        catch((FormatException) 
        {
            // error handling: conversion not possible
        }
        
        ...
        

        Regards Thomas

        www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
        Programmer - an organism that turns coffee into software.

        0 G 2 Replies Last reply
        0
        • T Thomas Weller 0

          You have to declare the argument as an array if it is one. Like so:

          static void function(ref T[] i)

          But your next line:

          int a = i[0];

          won't compile anyway, since the compiler cannot garantuee that T is of a type that is convertible to an int. Use something like this instead:

          static void function(ref T[] i) where T : struct
          {
          try
          {
          int a = Convert.ToInt(i[0]);

              // your code goes here
          }
          catch((FormatException) 
          {
              // error handling: conversion not possible
          }
          
          ...
          

          Regards Thomas

          www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
          Programmer - an organism that turns coffee into software.

          G Offline
          G Offline
          GuimaSun
          wrote on last edited by
          #4

          Thanks Thomas, I edit the question and explained it better. My problem is basically to access the "i" value when the function receive single types and arrays too, my problem is to get the value of each element when the type is an array (which I can check using i.GetType().IsArray). Thanks anyway.

          GuimaSun www.nexsun.com.br NEXSUN TechZone

          0 1 Reply Last reply
          0
          • T Thomas Weller 0

            You have to declare the argument as an array if it is one. Like so:

            static void function(ref T[] i)

            But your next line:

            int a = i[0];

            won't compile anyway, since the compiler cannot garantuee that T is of a type that is convertible to an int. Use something like this instead:

            static void function(ref T[] i) where T : struct
            {
            try
            {
            int a = Convert.ToInt(i[0]);

                // your code goes here
            }
            catch((FormatException) 
            {
                // error handling: conversion not possible
            }
            
            ...
            

            Regards Thomas

            www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
            Programmer - an organism that turns coffee into software.

            0 Offline
            0 Offline
            0x3c0
            wrote on last edited by
            #5

            Thomas Weller wrote:

            catch(FormatException)

            FTFY (extra bracket)

            1 Reply Last reply
            0
            • G GuimaSun

              Thanks Thomas, I edit the question and explained it better. My problem is basically to access the "i" value when the function receive single types and arrays too, my problem is to get the value of each element when the type is an array (which I can check using i.GetType().IsArray). Thanks anyway.

              GuimaSun www.nexsun.com.br NEXSUN TechZone

              0 Offline
              0 Offline
              0x3c0
              wrote on last edited by
              #6

              Then there's a small problem with my code. Try this:

              public static IEnumerable GetIEnumerable(T input)
              {
              if(input is IEnumerable)
              {
              foreach(T element in (input as IEnumerable))
              yield return element;
              }
              else
              yield return input;
              }

              As a bonus, this also deals with all IEnumerables (ArrayLists, Lists, etc), not just arrays. You could replace IEnumerable with T[] and get your original query.

              G 1 Reply Last reply
              0
              • 0 0x3c0

                Then there's a small problem with my code. Try this:

                public static IEnumerable GetIEnumerable(T input)
                {
                if(input is IEnumerable)
                {
                foreach(T element in (input as IEnumerable))
                yield return element;
                }
                else
                yield return input;
                }

                As a bonus, this also deals with all IEnumerables (ArrayLists, Lists, etc), not just arrays. You could replace IEnumerable with T[] and get your original query.

                G Offline
                G Offline
                GuimaSun
                wrote on last edited by
                #7

                It doesn't work: Unable to cast object of type 'System.Int32' to type 'System.Int32[]'.

                GuimaSun www.nexsun.com.br NEXSUN TechZone

                T 1 Reply Last reply
                0
                • G GuimaSun

                  It doesn't work: Unable to cast object of type 'System.Int32' to type 'System.Int32[]'.

                  GuimaSun www.nexsun.com.br NEXSUN TechZone

                  T Offline
                  T Offline
                  Thomas Weller 0
                  wrote on last edited by
                  #8

                  In this case you can simply declare two overloads, one for normal elements and one for arrays:

                  static void function(ref T i)
                  {
                  DoSomething(i);
                  }

                  static void function(ref T[] i)
                  {
                  foreach(T element in i)
                  {
                  DoSomething(element);
                  }
                  }

                  static void DoSomething(ref T i)
                  {
                  ...
                  }

                  Regards Thomas

                  www.thomas-weller.de Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning.
                  Programmer - an organism that turns coffee into software.

                  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