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. Generic method: Cast an object to a return type T

Generic method: Cast an object to a return type T

Scheduled Pinned Locked Moved C#
13 Posts 4 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.
  • S Offline
    S Offline
    Spunky Coder
    wrote on last edited by
    #1

    Hi All,

    Please let me know if we can cast a known type to a generic type...

    private static T InitData<T>(T dummyColl, int value)
    {
    List<SampleData> SampleColl = new List<SampleData> {
    new SampleData {
    Age = 23,
    Name="abc"
    }
    };
    /*I want to do something like this... */
    dummyColl = (T)SampleColl;
    }

    Is there any other way around to get this??

    "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

    0 R 2 Replies Last reply
    0
    • S Spunky Coder

      Hi All,

      Please let me know if we can cast a known type to a generic type...

      private static T InitData<T>(T dummyColl, int value)
      {
      List<SampleData> SampleColl = new List<SampleData> {
      new SampleData {
      Age = 23,
      Name="abc"
      }
      };
      /*I want to do something like this... */
      dummyColl = (T)SampleColl;
      }

      Is there any other way around to get this??

      "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

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

      It would probably throw an exception if you don't use a Collection type, but try (T)Convert.ChangeType(SampleColl, typeof(T)). Bear in mind that this will convert the list itself. If you want to convert the objects inside the list, then use SampleColl.Cast()

      _ S 2 Replies Last reply
      0
      • S Spunky Coder

        Hi All,

        Please let me know if we can cast a known type to a generic type...

        private static T InitData<T>(T dummyColl, int value)
        {
        List<SampleData> SampleColl = new List<SampleData> {
        new SampleData {
        Age = 23,
        Name="abc"
        }
        };
        /*I want to do something like this... */
        dummyColl = (T)SampleColl;
        }

        Is there any other way around to get this??

        "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

        R Offline
        R Offline
        Rob Philpott
        wrote on last edited by
        #3

        As it stands it won't work as T could be anything and so casting from SampleColl to T may very well not work. Try this, use 'as':

        dummyColl = SampleColl as T;

        you'll need (I think) to add a constraint to your generic method

        private static T InitData<T>(T dummyColl, int value) where T: class

        .. because T might be a value type and you need to constrain it to reference types to use as. If you're not familiar with constraining generic types and methods have a read up on that - that should help you quite a bit but it's hard to offer advice without knowing what derives from what.

        Regards, Rob Philpott.

        S 1 Reply Last reply
        0
        • 0 0x3c0

          It would probably throw an exception if you don't use a Collection type, but try (T)Convert.ChangeType(SampleColl, typeof(T)). Bear in mind that this will convert the list itself. If you want to convert the objects inside the list, then use SampleColl.Cast()

          _ Offline
          _ Offline
          _groo_
          wrote on last edited by
          #4

          It is not very clear from your sample what you are trying to do. If you are doing this to cast a collection (hence the dummyColl name?), you would probably want to do something like:

          private static List CastToDerivedType(List list) where T : BaseType
          {
          List result = new List();
          foreach (BaseType item in list)
          result.Add(item as T);
          return result;
          }

          Try explaining what is your goal first.

          1 Reply Last reply
          0
          • 0 0x3c0

            It would probably throw an exception if you don't use a Collection type, but try (T)Convert.ChangeType(SampleColl, typeof(T)). Bear in mind that this will convert the list itself. If you want to convert the objects inside the list, then use SampleColl.Cast()

            S Offline
            S Offline
            Spunky Coder
            wrote on last edited by
            #5

            Great! It is working fine...but FYI earlier i have used

            Convert.ChangeType(SampleColl, dummyColl.GetType())

            but still i don't understand how come i missed the explicit casting (T) :omg: :doh: :-\ Anyhow thanks for guiding me...

            "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

            _ 1 Reply Last reply
            0
            • R Rob Philpott

              As it stands it won't work as T could be anything and so casting from SampleColl to T may very well not work. Try this, use 'as':

              dummyColl = SampleColl as T;

              you'll need (I think) to add a constraint to your generic method

              private static T InitData<T>(T dummyColl, int value) where T: class

              .. because T might be a value type and you need to constrain it to reference types to use as. If you're not familiar with constraining generic types and methods have a read up on that - that should help you quite a bit but it's hard to offer advice without knowing what derives from what.

              Regards, Rob Philpott.

              S Offline
              S Offline
              Spunky Coder
              wrote on last edited by
              #6

              Rob Philpott wrote:

              T could be anything and so casting from SampleColl to T may very well not work

              I agree with you...but at the calling site itself I have confined T for only two data types (as per the requirement). So in my code there is never a chance that T is a value type :)

              Rob Philpott wrote:

              private static T InitData(T dummyColl, int value) where T: class

              I've used this but frankly I don't understand its usage...even with that 'where' clause I'm able to do something like this without any compiler error.

              int i=2;
              (T)Convert.ChangeType(i, dummyColl.GetType())

              So whether I use this constraint or not it throws the error at runtime only.Can you please let me know why is it happening?

              "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

              R 1 Reply Last reply
              0
              • S Spunky Coder

                Great! It is working fine...but FYI earlier i have used

                Convert.ChangeType(SampleColl, dummyColl.GetType())

                but still i don't understand how come i missed the explicit casting (T) :omg: :doh: :-\ Anyhow thanks for guiding me...

                "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                _ Offline
                _ Offline
                _groo_
                wrote on last edited by
                #7

                Just a note - you should note that this line:

                dummyColl = (T)SampleColl;

                doesn't do anything to the actual dummyColl being passed to the method. So this kind of casting at the end of your method doesn't do anything.

                S 1 Reply Last reply
                0
                • S Spunky Coder

                  Rob Philpott wrote:

                  T could be anything and so casting from SampleColl to T may very well not work

                  I agree with you...but at the calling site itself I have confined T for only two data types (as per the requirement). So in my code there is never a chance that T is a value type :)

                  Rob Philpott wrote:

                  private static T InitData(T dummyColl, int value) where T: class

                  I've used this but frankly I don't understand its usage...even with that 'where' clause I'm able to do something like this without any compiler error.

                  int i=2;
                  (T)Convert.ChangeType(i, dummyColl.GetType())

                  So whether I use this constraint or not it throws the error at runtime only.Can you please let me know why is it happening?

                  "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                  R Offline
                  R Offline
                  Rob Philpott
                  wrote on last edited by
                  #8

                  Spunky Coder wrote:

                  but at the calling site itself I have confined T for only two data types

                  That's unimportant. The compiler needs to compile your function, and in order to do that it needs to know a bit about T. If it knows nothing about T, it has to assume it could be anything and therefore won't accept your cast. By constraining the function, your telling the compiler something about T, enough for it to be satisfied that the cast will always work. Don't forget your assembly might be used in other projects written by other people- how can you guarantee that they'll call it the correct way?

                  Spunky Coder wrote:

                  So whether I use this constraint or not it throws the error at runtime only.Can you please let me know why is it happening?

                  What's the error?

                  Regards, Rob Philpott.

                  S 1 Reply Last reply
                  0
                  • _ _groo_

                    Just a note - you should note that this line:

                    dummyColl = (T)SampleColl;

                    doesn't do anything to the actual dummyColl being passed to the method. So this kind of casting at the end of your method doesn't do anything.

                    S Offline
                    S Offline
                    Spunky Coder
                    wrote on last edited by
                    #9

                    I agree...Actually while working for the solution I've passed the dummyColl argument to the method that's because I thought I can get the T type by using dummyColl.GetType().(But I forgot that, to get Type there is actually 'typeof' exists in .NET :-\ ) Also using

                    veki-peki wrote:

                    dummyColl = (T)SampleColl;

                    gives me a compiler error!!! Cannot convert List type to T

                    "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                    1 Reply Last reply
                    0
                    • R Rob Philpott

                      Spunky Coder wrote:

                      but at the calling site itself I have confined T for only two data types

                      That's unimportant. The compiler needs to compile your function, and in order to do that it needs to know a bit about T. If it knows nothing about T, it has to assume it could be anything and therefore won't accept your cast. By constraining the function, your telling the compiler something about T, enough for it to be satisfied that the cast will always work. Don't forget your assembly might be used in other projects written by other people- how can you guarantee that they'll call it the correct way?

                      Spunky Coder wrote:

                      So whether I use this constraint or not it throws the error at runtime only.Can you please let me know why is it happening?

                      What's the error?

                      Regards, Rob Philpott.

                      S Offline
                      S Offline
                      Spunky Coder
                      wrote on last edited by
                      #10

                      Well, the error is a runtime error. "Cannot convert System.Int32 to List". Here List is the type of T passed to this method. Even when I don't use the 'where' class, the same runtime error is shown when executing the line

                      int i=2;
                      (T)Convert.ChangeType(i, dummyColl.GetType())

                      "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                      R 1 Reply Last reply
                      0
                      • S Spunky Coder

                        Well, the error is a runtime error. "Cannot convert System.Int32 to List". Here List is the type of T passed to this method. Even when I don't use the 'where' class, the same runtime error is shown when executing the line

                        int i=2;
                        (T)Convert.ChangeType(i, dummyColl.GetType())

                        "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                        R Offline
                        R Offline
                        Rob Philpott
                        wrote on last edited by
                        #11

                        Well, I'm not sure what the question is here. Of course, you cannot cast an int to a list. They're completely different things. Steer clear of Convert.ChangeType. You won't get any compile time checking with this and compiler errors are always more favourable than runtime ones.

                        Regards, Rob Philpott.

                        S 1 Reply Last reply
                        0
                        • R Rob Philpott

                          Well, I'm not sure what the question is here. Of course, you cannot cast an int to a list. They're completely different things. Steer clear of Convert.ChangeType. You won't get any compile time checking with this and compiler errors are always more favourable than runtime ones.

                          Regards, Rob Philpott.

                          S Offline
                          S Offline
                          Spunky Coder
                          wrote on last edited by
                          #12

                          Hmmm...I was asking for the use of 'where T:class'. Anyhow I got it from google about the Constraints on Type Parameters. Thanks for the information. :)

                          "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                          _ 1 Reply Last reply
                          0
                          • S Spunky Coder

                            Hmmm...I was asking for the use of 'where T:class'. Anyhow I got it from google about the Constraints on Type Parameters. Thanks for the information. :)

                            "Don't worry if it doesn't work right. If everything did, you'd be out of a job." (Mosher's Law of Software Engineering)

                            _ Offline
                            _ Offline
                            _groo_
                            wrote on last edited by
                            #13

                            But you still didn't say why you are trying to do this? Casting Int32 to a List<> doesn't make much sense, so it is natural that you will get this error. There may be a better solution to your problem, so try to explain what is the actual problem that got you thinking about casting with generic parameters?

                            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