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. Small c# challenge [modified]

Small c# challenge [modified]

Scheduled Pinned Locked Moved The Lounge
csharpdatabasecomtoolsquestion
34 Posts 13 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.
  • G Giorgi Dalakishvili

    Let's say you have this class:

    class myClass
    {
    public double? Foo;
    }

    and this piece of code:

    myClass temp=new myClass()
    SqlDataReader rd = GetDataSomeHow();

    if(rd.IsDBNull(0))
    temp.Foo = null;
    else
    temp.Foo = rd.GetDouble(0);

    Rewrite the above statement without if. [Edit] One line solution Sorry if it's too easy for you :) Here is the solution in case you can't solve it: Solution[^]

    Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

    modified on Thursday, October 23, 2008 11:23 AM

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

    What BS. A tertiary operator is just like an if. [edit] And the fact that nullable types didn't resolve the mismatch between null and DBNull pisses me off to no end.[/edit] [edit2] And yeah, you can really get rid of the if this way:

    object Foo;
    ...
    temp.Foo=rd[0];

    :laugh: Marc

    Thyme In The Country Interacx My Blog

    E C G L 4 Replies Last reply
    0
    • G Giorgi Dalakishvili

      Let's say you have this class:

      class myClass
      {
      public double? Foo;
      }

      and this piece of code:

      myClass temp=new myClass()
      SqlDataReader rd = GetDataSomeHow();

      if(rd.IsDBNull(0))
      temp.Foo = null;
      else
      temp.Foo = rd.GetDouble(0);

      Rewrite the above statement without if. [Edit] One line solution Sorry if it's too easy for you :) Here is the solution in case you can't solve it: Solution[^]

      Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

      modified on Thursday, October 23, 2008 11:23 AM

      C Offline
      C Offline
      Chris Losinger
      wrote on last edited by
      #4

      try
      {
      temp.Foo = rd.GetDouble(0);
      }
      catch (Exception e)
      {
      temp.Foo = null;
      }

      that's assuming GetDouble will throw an exception on null.

      image processing toolkits | batch image processing

      G 1 Reply Last reply
      0
      • G Giorgi Dalakishvili

        Let's say you have this class:

        class myClass
        {
        public double? Foo;
        }

        and this piece of code:

        myClass temp=new myClass()
        SqlDataReader rd = GetDataSomeHow();

        if(rd.IsDBNull(0))
        temp.Foo = null;
        else
        temp.Foo = rd.GetDouble(0);

        Rewrite the above statement without if. [Edit] One line solution Sorry if it's too easy for you :) Here is the solution in case you can't solve it: Solution[^]

        Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

        modified on Thursday, October 23, 2008 11:23 AM

        E Offline
        E Offline
        Ennis Ray Lynch Jr
        wrote on last edited by
        #5

        temp.Foo = rd[0] == DbNull.Value ? null : (double)rd[0]

        Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
        Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
        Most of this sig is for Google, not ego.

        E G R 3 Replies Last reply
        0
        • M Marc Clifton

          What BS. A tertiary operator is just like an if. [edit] And the fact that nullable types didn't resolve the mismatch between null and DBNull pisses me off to no end.[/edit] [edit2] And yeah, you can really get rid of the if this way:

          object Foo;
          ...
          temp.Foo=rd[0];

          :laugh: Marc

          Thyme In The Country Interacx My Blog

          E Offline
          E Offline
          Ennis Ray Lynch Jr
          wrote on last edited by
          #6

          Me too.

          Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
          Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
          Most of this sig is for Google, not ego.

          1 Reply Last reply
          0
          • E Ennis Ray Lynch Jr

            temp.Foo = rd[0] == DbNull.Value ? null : (double)rd[0]

            Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
            Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
            Most of this sig is for Google, not ego.

            E Offline
            E Offline
            Ennis Ray Lynch Jr
            wrote on last edited by
            #7

            you could also rewrite the query

            SELECT
            isnul(foo, '')
            FROM
            wherever

            Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
            Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
            Most of this sig is for Google, not ego.

            C J G 3 Replies Last reply
            0
            • M Marc Clifton

              What BS. A tertiary operator is just like an if. [edit] And the fact that nullable types didn't resolve the mismatch between null and DBNull pisses me off to no end.[/edit] [edit2] And yeah, you can really get rid of the if this way:

              object Foo;
              ...
              temp.Foo=rd[0];

              :laugh: Marc

              Thyme In The Country Interacx My Blog

              C Offline
              C Offline
              cpkilekofp
              wrote on last edited by
              #8

              Marc Clifton wrote:

              And yeah, you can really get rid of the if this way: object Foo;...temp.Foo=rd[0];

              That's what I would have thought from the C# 2.0 spec. But I have to ask: have you tried it, and observed it to work?

              M 1 Reply Last reply
              0
              • E Ennis Ray Lynch Jr

                you could also rewrite the query

                SELECT
                isnul(foo, '')
                FROM
                wherever

                Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                Most of this sig is for Google, not ego.

                C Offline
                C Offline
                cpkilekofp
                wrote on last edited by
                #9

                Ennis Ray Lynch, Jr. wrote:

                you could also rewrite the query SELECT isnul(foo, '')FROM wherever

                Oh, yes, I ALWAYS want a VARCHAR(0) returned when I'm expecting a double :laugh:

                E 1 Reply Last reply
                0
                • C cpkilekofp

                  Ennis Ray Lynch, Jr. wrote:

                  you could also rewrite the query SELECT isnul(foo, '')FROM wherever

                  Oh, yes, I ALWAYS want a VARCHAR(0) returned when I'm expecting a double :laugh:

                  E Offline
                  E Offline
                  Ennis Ray Lynch Jr
                  wrote on last edited by
                  #10

                  I wasn't paying any attention. I just squeezed in an emergency production db fix using that exact code so I naturally used the ''.

                  Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                  Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                  Most of this sig is for Google, not ego.

                  C 1 Reply Last reply
                  0
                  • E Ennis Ray Lynch Jr

                    you could also rewrite the query

                    SELECT
                    isnul(foo, '')
                    FROM
                    wherever

                    Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                    Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                    Most of this sig is for Google, not ego.

                    J Offline
                    J Offline
                    James Simpson
                    wrote on last edited by
                    #11

                    You could also write a set of extension methods for DbDataReader eg public static double? GetDoubleOrDefault(this DbDataReader src, int index) { return GetDoubleOrDefault(src, index, 0); } public static double? GetDoubleOrDefault(this DbDataReader src, int index, double? def) { return this.IsDbNull(index) == true ? def : this.GetDouble(index) } then your example might be: temp.Foo = rd.GetDoubleOrDefault(0); or temp.Foo = rd.GetDoubleOrDefault(0, 0);

                    James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
                    Mitch Hedberg

                    S 1 Reply Last reply
                    0
                    • J James Simpson

                      You could also write a set of extension methods for DbDataReader eg public static double? GetDoubleOrDefault(this DbDataReader src, int index) { return GetDoubleOrDefault(src, index, 0); } public static double? GetDoubleOrDefault(this DbDataReader src, int index, double? def) { return this.IsDbNull(index) == true ? def : this.GetDouble(index) } then your example might be: temp.Foo = rd.GetDoubleOrDefault(0); or temp.Foo = rd.GetDoubleOrDefault(0, 0);

                      James Simpson Web Developer imebgo@hotmail.com P S - This is what part of the alphabet would look like if Q and R were eliminated
                      Mitch Hedberg

                      S Offline
                      S Offline
                      Simon P Stevens
                      wrote on last edited by
                      #12

                      I like that. Keeps the code nice and readable.

                      Simon

                      1 Reply Last reply
                      0
                      • G Giorgi Dalakishvili

                        Let's say you have this class:

                        class myClass
                        {
                        public double? Foo;
                        }

                        and this piece of code:

                        myClass temp=new myClass()
                        SqlDataReader rd = GetDataSomeHow();

                        if(rd.IsDBNull(0))
                        temp.Foo = null;
                        else
                        temp.Foo = rd.GetDouble(0);

                        Rewrite the above statement without if. [Edit] One line solution Sorry if it's too easy for you :) Here is the solution in case you can't solve it: Solution[^]

                        Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                        modified on Thursday, October 23, 2008 11:23 AM

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #13

                        I wouldn't use the tertiary operator in this case either, most times I use it to avoid a local variable: System.Console.Writeline ( rd [ 0 ] == System.DBNull.Value ? "null" : rd [ 0 ].ToString() ) ; In this case I'd initialize Foo to null in the class (shouldn't it be anyway?) and then:

                        if ( rd [ 0 ] != System.DBNull.Value )
                        {
                        temp.Foo = (double) rd [ 0 ] ;
                        }

                        But this kind of stuff belongs encapsulated in something, perhaps pass the DataReader to the constructor of myClass and hide the details there. This is why my wrapper for ExecuteScalar requires the user to pass in a value to use in case of null.

                            public virtual T
                            ExecuteScalar<T>
                            (
                                T IfNull
                            )
                            {
                                lock ( this.cmd )
                                {
                                    **T    result    = IfNull ;**
                                    bool wasclosed = this.IsClosed ;
                                    
                                    try
                                    {
                                        object temp ;
                                        
                                        if ( wasclosed )
                                        {
                                            this.Open() ;
                                        }
                        
                                        temp = this.cmd.ExecuteScalar() ;
                        
                                        **if ( ( temp != null ) && ( temp != System.DBNull.Value ) )
                                        {
                                            result = (T) temp ;
                                        }**
                                    }
                                    catch ( System.Exception err )
                                    {
                                        throw ( WrapDataException ( "ExecuteScalar" , this.cmd , err ) ) ;
                                    }
                                    finally
                                    {
                                        if ( wasclosed )
                                        {
                                            this.Close() ;
                                        }
                                    }
                        
                                    return ( result ) ;
                                }
                            }
                        
                        1 Reply Last reply
                        0
                        • M Marc Clifton

                          What BS. A tertiary operator is just like an if. [edit] And the fact that nullable types didn't resolve the mismatch between null and DBNull pisses me off to no end.[/edit] [edit2] And yeah, you can really get rid of the if this way:

                          object Foo;
                          ...
                          temp.Foo=rd[0];

                          :laugh: Marc

                          Thyme In The Country Interacx My Blog

                          G Offline
                          G Offline
                          Giorgi Dalakishvili
                          wrote on last edited by
                          #14

                          rd[0] returns object, not double.

                          Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                          M 1 Reply Last reply
                          0
                          • E Ennis Ray Lynch Jr

                            you could also rewrite the query

                            SELECT
                            isnul(foo, '')
                            FROM
                            wherever

                            Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                            Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                            Most of this sig is for Google, not ego.

                            G Offline
                            G Offline
                            Giorgi Dalakishvili
                            wrote on last edited by
                            #15

                            In that case how will you know if the database contained zero or it was null and isnull turned it into zero?

                            Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                            E 1 Reply Last reply
                            0
                            • G Giorgi Dalakishvili

                              In that case how will you know if the database contained zero or it was null and isnull turned it into zero?

                              Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                              E Offline
                              E Offline
                              Ennis Ray Lynch Jr
                              wrote on last edited by
                              #16

                              That is why I usually use the ternary operator. However, if you are using .NET 1.0 or 1.1 my solution is valid for your question.

                              Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                              Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                              Most of this sig is for Google, not ego.

                              1 Reply Last reply
                              0
                              • C Chris Losinger

                                try
                                {
                                temp.Foo = rd.GetDouble(0);
                                }
                                catch (Exception e)
                                {
                                temp.Foo = null;
                                }

                                that's assuming GetDouble will throw an exception on null.

                                image processing toolkits | batch image processing

                                G Offline
                                G Offline
                                Giorgi Dalakishvili
                                wrote on last edited by
                                #17

                                What if you have several properties in your class? Code will get very ugly.

                                Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                C P 2 Replies Last reply
                                0
                                • E Ennis Ray Lynch Jr

                                  temp.Foo = rd[0] == DbNull.Value ? null : (double)rd[0]

                                  Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                                  Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                                  Most of this sig is for Google, not ego.

                                  G Offline
                                  G Offline
                                  Giorgi Dalakishvili
                                  wrote on last edited by
                                  #18

                                  Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'double' Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                  modified on Thursday, October 23, 2008 11:33 AM

                                  E 1 Reply Last reply
                                  0
                                  • G Giorgi Dalakishvili

                                    Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'double' Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                    modified on Thursday, October 23, 2008 11:33 AM

                                    E Offline
                                    E Offline
                                    Ennis Ray Lynch Jr
                                    wrote on last edited by
                                    #19

                                    Follow the subthread I have already responded to this, it was a mistake on my part and should have been isnull(foo, 0) or more fully isnull(foo, cast(0 as float))

                                    Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                                    Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                                    Most of this sig is for Google, not ego.

                                    G 1 Reply Last reply
                                    0
                                    • G Giorgi Dalakishvili

                                      What if you have several properties in your class? Code will get very ugly.

                                      Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                      C Offline
                                      C Offline
                                      Chris Losinger
                                      wrote on last edited by
                                      #20

                                      1. initialize temp's properties to null 2. try { do all your Get*() calls } or, write Get*Default functions which do the null test and assign either the recordset value, or a default value in case the field is null.

                                      image processing toolkits | batch image processing

                                      1 Reply Last reply
                                      0
                                      • E Ennis Ray Lynch Jr

                                        Follow the subthread I have already responded to this, it was a mistake on my part and should have been isnull(foo, 0) or more fully isnull(foo, cast(0 as float))

                                        Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                                        Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                                        Most of this sig is for Google, not ego.

                                        G Offline
                                        G Offline
                                        Giorgi Dalakishvili
                                        wrote on last edited by
                                        #21

                                        Sorry, some characters got swallowed. The code will not compile.

                                        Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                        E 1 Reply Last reply
                                        0
                                        • G Giorgi Dalakishvili

                                          Sorry, some characters got swallowed. The code will not compile.

                                          Giorgi Dalakishvili #region signature My Articles / My Latest Article[^] / My blog[^] #endregion

                                          E Offline
                                          E Offline
                                          Ennis Ray Lynch Jr
                                          wrote on last edited by
                                          #22

                                          Ah, yeah, sometimes the ternary is a bear because of the typing. Cast using (double?) instead I believe. Really, however, if this is to migrate into a programming question it should not be in the lounge. The logic is inferrable from what I wrote.

                                          Need software developed? Offering C# development all over the United States, ERL GLOBAL, Inc is the only call you will have to make.
                                          Happiness in intelligent people is the rarest thing I know. -- Ernest Hemingway
                                          Most of this sig is for Google, not ego.

                                          G 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