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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. NULLABLE type

NULLABLE type

Scheduled Pinned Locked Moved C#
question
17 Posts 6 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.
  • R RINSON VARGHESE

    how nullable type different from normal type.i knew that for nullable type we can assign NULL value(specialy for value types)..i want to know what is the speciality in nullable type so that v can assign NULL to that...i am also want to know nullable types are another type or what?

    K Offline
    K Offline
    Keith Barrow
    wrote on last edited by
    #2

    This will tell you everything you need. c# Nullable types[^]

    CCC solved so far: 2 (including a Hard One!)

    1 Reply Last reply
    0
    • R RINSON VARGHESE

      how nullable type different from normal type.i knew that for nullable type we can assign NULL value(specialy for value types)..i want to know what is the speciality in nullable type so that v can assign NULL to that...i am also want to know nullable types are another type or what?

      A Offline
      A Offline
      Abhishek Sur
      wrote on last edited by
      #3

      Nullable Types can take Nulls. Generally Valuetypes couldnt have Null assigned to it, it should always assign default(type) In case of Nullables, you can assign nulls int? x = null; if(x.HasValue) int y = x.Value; // x.Value will point to original value. So you can say Nullable types is just a wrapper. :-D For further Enquery Read Here : C# 2.0 Nullable Types[^] Or Working with Nullable Types in C#[^] :thumbsup:

      Abhishek Sur **Don't forget to click "Good Answer" if you like this Solution.


      My Latest Articles-->** Microsoft Bing MAP using Javascript
      CLR objects in SQL Server 2005
      Uncommon C# Keywords
      /xml>

      1 Reply Last reply
      0
      • R RINSON VARGHESE

        how nullable type different from normal type.i knew that for nullable type we can assign NULL value(specialy for value types)..i want to know what is the speciality in nullable type so that v can assign NULL to that...i am also want to know nullable types are another type or what?

        K Offline
        K Offline
        Keith Barrow
        wrote on last edited by
        #4

        OK, so my facecious comment wasn't so helpful. Primitive types (int, bool etc) are not nullable, the classic exception to this is string, which can be set to null. Objects of type object and derived from object are nullable. Nullable types allow null values on "primitive" types (they also have HasValue property): i.e.

        int foo = null; //Design time/ compile time error : assigning null to non-nullable primative type
        int? bar = null; //OK
        string baz = null; //OK, string is nullable.
        string? quux = null; //Design time / compile time error : string is nullable
        Nullable<string> foo1 = null; //Design time/ compile time error : string is nullable
        object bar1 = null; //OK: Object nullable
        MyClass baz1 = null; //OK: Object nullable as is an object.

        Personally, I'd stear clear of nullable values where possible, as you will need to perpetually check the value is not null and other types of evil ensue.

        CCC solved so far: 2 (including a Hard One!)

        A V 2 Replies Last reply
        0
        • K Keith Barrow

          OK, so my facecious comment wasn't so helpful. Primitive types (int, bool etc) are not nullable, the classic exception to this is string, which can be set to null. Objects of type object and derived from object are nullable. Nullable types allow null values on "primitive" types (they also have HasValue property): i.e.

          int foo = null; //Design time/ compile time error : assigning null to non-nullable primative type
          int? bar = null; //OK
          string baz = null; //OK, string is nullable.
          string? quux = null; //Design time / compile time error : string is nullable
          Nullable<string> foo1 = null; //Design time/ compile time error : string is nullable
          object bar1 = null; //OK: Object nullable
          MyClass baz1 = null; //OK: Object nullable as is an object.

          Personally, I'd stear clear of nullable values where possible, as you will need to perpetually check the value is not null and other types of evil ensue.

          CCC solved so far: 2 (including a Hard One!)

          A Offline
          A Offline
          Abhishek Sur
          wrote on last edited by
          #5

          keefb wrote:

          Personally, I'd stear clear of nullable values where possible, as you will need to perpetually check the value is not null and other types of evil ensue.

          yaah ... me too .. :-D

          Abhishek Sur **Don't forget to click "Good Answer" if you like this Solution.


          My Latest Articles-->** Microsoft Bing MAP using Javascript
          CLR objects in SQL Server 2005
          Uncommon C# Keywords
          /xml>

          1 Reply Last reply
          0
          • K Keith Barrow

            OK, so my facecious comment wasn't so helpful. Primitive types (int, bool etc) are not nullable, the classic exception to this is string, which can be set to null. Objects of type object and derived from object are nullable. Nullable types allow null values on "primitive" types (they also have HasValue property): i.e.

            int foo = null; //Design time/ compile time error : assigning null to non-nullable primative type
            int? bar = null; //OK
            string baz = null; //OK, string is nullable.
            string? quux = null; //Design time / compile time error : string is nullable
            Nullable<string> foo1 = null; //Design time/ compile time error : string is nullable
            object bar1 = null; //OK: Object nullable
            MyClass baz1 = null; //OK: Object nullable as is an object.

            Personally, I'd stear clear of nullable values where possible, as you will need to perpetually check the value is not null and other types of evil ensue.

            CCC solved so far: 2 (including a Hard One!)

            V Offline
            V Offline
            vtchris peterson
            wrote on last edited by
            #6

            There are plenty of good uses for Nullable. Think of a case when you have an optional value, (e.g. a field in a database), what better way to indicate a missing value than with null? Oftentimes, people use -1 (or some other reserved value) to indicate that something is missing; using nullables is an elegant way to indicate ommision without eating into possibly valid values.

            K 1 Reply Last reply
            0
            • V vtchris peterson

              There are plenty of good uses for Nullable. Think of a case when you have an optional value, (e.g. a field in a database), what better way to indicate a missing value than with null? Oftentimes, people use -1 (or some other reserved value) to indicate that something is missing; using nullables is an elegant way to indicate ommision without eating into possibly valid values.

              K Offline
              K Offline
              Keith Barrow
              wrote on last edited by
              #7

              vtpdawg wrote:

              There are plenty of good uses for Nullable.

              True, and as I said, I wouldn't use null unless I had to. Where a value is truly unkown then I would use a null as you suggest, but instances of this are less common than represented in code bases I have seen. If you see a nullable value you should really think twice to ensure it truly is unkown. A case in point is the -1 example you give. This is my view is preferable than having rogue nulls hanging around. From the DB point of view, anyone writing SQL against a table that has nullable columns has to be aware that null is a possibilty. Wheras say -1 relates to an "Unset" state, this is still normally a valid state . On the code front, I remember reading somewhere that 50%(this seems too high, but it is a large percentage) of all exceptions are null reference exceptions. The is lots of literature out there on both sides of the argument, personally I think nulls are evil, but sometimes a necessary one.

              CCC solved so far: 2 (including a Hard One!)

              R V 2 Replies Last reply
              0
              • K Keith Barrow

                vtpdawg wrote:

                There are plenty of good uses for Nullable.

                True, and as I said, I wouldn't use null unless I had to. Where a value is truly unkown then I would use a null as you suggest, but instances of this are less common than represented in code bases I have seen. If you see a nullable value you should really think twice to ensure it truly is unkown. A case in point is the -1 example you give. This is my view is preferable than having rogue nulls hanging around. From the DB point of view, anyone writing SQL against a table that has nullable columns has to be aware that null is a possibilty. Wheras say -1 relates to an "Unset" state, this is still normally a valid state . On the code front, I remember reading somewhere that 50%(this seems too high, but it is a large percentage) of all exceptions are null reference exceptions. The is lots of literature out there on both sides of the argument, personally I think nulls are evil, but sometimes a necessary one.

                CCC solved so far: 2 (including a Hard One!)

                R Offline
                R Offline
                Rick Shaub
                wrote on last edited by
                #8

                What do you think of reference types? They should be checked for null as well. Plus, there are many more reference types than value types.

                K 1 Reply Last reply
                0
                • K Keith Barrow

                  vtpdawg wrote:

                  There are plenty of good uses for Nullable.

                  True, and as I said, I wouldn't use null unless I had to. Where a value is truly unkown then I would use a null as you suggest, but instances of this are less common than represented in code bases I have seen. If you see a nullable value you should really think twice to ensure it truly is unkown. A case in point is the -1 example you give. This is my view is preferable than having rogue nulls hanging around. From the DB point of view, anyone writing SQL against a table that has nullable columns has to be aware that null is a possibilty. Wheras say -1 relates to an "Unset" state, this is still normally a valid state . On the code front, I remember reading somewhere that 50%(this seems too high, but it is a large percentage) of all exceptions are null reference exceptions. The is lots of literature out there on both sides of the argument, personally I think nulls are evil, but sometimes a necessary one.

                  CCC solved so far: 2 (including a Hard One!)

                  V Offline
                  V Offline
                  vtchris peterson
                  wrote on last edited by
                  #9

                  I don't see how if (val == -1) is much different than if (val == null) null is not something to be feared, the prudent developer should just be in the practice of always considering null when dereferencing objects. You mention "rogue nulls hanging around" like they're some loitering punks harassing passerbys :) That being said, I've only ever used nullables in data access layers (LLBLGen and LINQ actually generate code with nullables) and a specialized encoding library where it was perfectly valid to omit property values, including value types.

                  K M 2 Replies Last reply
                  0
                  • V vtchris peterson

                    I don't see how if (val == -1) is much different than if (val == null) null is not something to be feared, the prudent developer should just be in the practice of always considering null when dereferencing objects. You mention "rogue nulls hanging around" like they're some loitering punks harassing passerbys :) That being said, I've only ever used nullables in data access layers (LLBLGen and LINQ actually generate code with nullables) and a specialized encoding library where it was perfectly valid to omit property values, including value types.

                    K Offline
                    K Offline
                    Keith Barrow
                    wrote on last edited by
                    #10

                    vtpdawg wrote:

                    I don't see how if (val == -1) is much different than if (val == null)

                    Of course, if you take this as an example there is little difference. Consider the example of the number indicating a "status" of some kind to display on the UI. One implementation (albeit artificial and not necessarily the best) would be to reference with number with a dictionary:

                    Dictionary <int,string> lookup;

                    public void SetupLookup()
                    {
                    lookup = new Dictionary <int,string>();
                    lookup.Add(-1, "Unkown");
                    lookup.Add(0,"Naughty");
                    lookup.Add(1, "Nice");
                    }

                    //This is the "clean" non-nullable example
                    public void string Lookup(int foo)
                    {
                    return lookup[foo];
                    }

                    //This is less clean nullable example, for this example the -1 key in the dictionary is not needed....
                    public void string Lookup2(int& foo)
                    {
                    if(foo.HasValue)
                    return lookup[foo];
                    return "Unknown";
                    }

                    This example isn't perfect, but serves to illustrate the point. Now, we need to handle the null properly in the nullable type case . Once you decide to put the nullable type in, this sort of checking necessarily propagates throughout the code if the code is written to be robust. Additionally, there are fewer problems binding non-nullable types as you can (as in the above example) resolve -1 to something directly.

                    vtpdawg wrote:

                    You mention "rogue nulls hanging around" like they're some loitering punks harassing passerbys

                    In a database context, this is exactly what they are like. :-)

                    vtpdawg wrote:

                    null is not something to be feared, the prudent developer should just be in the practice of always considering null when dereferencing objects.

                    Agreed, but it is surely better to factor these out by design? One of the things I don't like about c# is the fact that objects are nullable by default (unlike c++) because we have to write a boilerplate code to allow for this. The point I was trying to get across was just that nulls are best avoided and rarely needed, not that nulls should never be used. There are good counter arguments to everything I have said here, many of which I have sympathy with, it's opinion that the arguments in favour of avoiding nulls outweigh these (Others of course disagree!).

                    CCC solved so far: 2 (including a Hard One!)

                    V 1 Reply Last reply
                    0
                    • R Rick Shaub

                      What do you think of reference types? They should be checked for null as well. Plus, there are many more reference types than value types.

                      K Offline
                      K Offline
                      Keith Barrow
                      wrote on last edited by
                      #11

                      True, and this is a deficiency in the framework in my opinion( see my other post on this thread for a partial explanation why, and I again stress this is my opinion, others differ and anyone reading this should, as ever, evaluate and form their own). Additionally, reference types passed into a function are mutable by the function, which can lead to unexpected consequences if that method is poorly implemented. Again this is one of the things I think languages like c++ handle better. I'm certain the .net framework designers had good reasons to choose the reference types over value types when designing the language, just from my point of view it would have been nicer if they hadn't. Saying that, I dare say Microsoft put a few bright minds on the framework team :-)

                      CCC solved so far: 2 (including a Hard One!)

                      1 Reply Last reply
                      0
                      • V vtchris peterson

                        I don't see how if (val == -1) is much different than if (val == null) null is not something to be feared, the prudent developer should just be in the practice of always considering null when dereferencing objects. You mention "rogue nulls hanging around" like they're some loitering punks harassing passerbys :) That being said, I've only ever used nullables in data access layers (LLBLGen and LINQ actually generate code with nullables) and a specialized encoding library where it was perfectly valid to omit property values, including value types.

                        M Offline
                        M Offline
                        Mycroft Holmes
                        wrote on last edited by
                        #12

                        My biggest issue is that when you aggregate a field in SQL you need to deal with the potential null values, you end up with IsNull(Field,0) all over the place just to deal with them. I often put in a default of 0.

                        K 1 Reply Last reply
                        0
                        • K Keith Barrow

                          vtpdawg wrote:

                          I don't see how if (val == -1) is much different than if (val == null)

                          Of course, if you take this as an example there is little difference. Consider the example of the number indicating a "status" of some kind to display on the UI. One implementation (albeit artificial and not necessarily the best) would be to reference with number with a dictionary:

                          Dictionary <int,string> lookup;

                          public void SetupLookup()
                          {
                          lookup = new Dictionary <int,string>();
                          lookup.Add(-1, "Unkown");
                          lookup.Add(0,"Naughty");
                          lookup.Add(1, "Nice");
                          }

                          //This is the "clean" non-nullable example
                          public void string Lookup(int foo)
                          {
                          return lookup[foo];
                          }

                          //This is less clean nullable example, for this example the -1 key in the dictionary is not needed....
                          public void string Lookup2(int& foo)
                          {
                          if(foo.HasValue)
                          return lookup[foo];
                          return "Unknown";
                          }

                          This example isn't perfect, but serves to illustrate the point. Now, we need to handle the null properly in the nullable type case . Once you decide to put the nullable type in, this sort of checking necessarily propagates throughout the code if the code is written to be robust. Additionally, there are fewer problems binding non-nullable types as you can (as in the above example) resolve -1 to something directly.

                          vtpdawg wrote:

                          You mention "rogue nulls hanging around" like they're some loitering punks harassing passerbys

                          In a database context, this is exactly what they are like. :-)

                          vtpdawg wrote:

                          null is not something to be feared, the prudent developer should just be in the practice of always considering null when dereferencing objects.

                          Agreed, but it is surely better to factor these out by design? One of the things I don't like about c# is the fact that objects are nullable by default (unlike c++) because we have to write a boilerplate code to allow for this. The point I was trying to get across was just that nulls are best avoided and rarely needed, not that nulls should never be used. There are good counter arguments to everything I have said here, many of which I have sympathy with, it's opinion that the arguments in favour of avoiding nulls outweigh these (Others of course disagree!).

                          CCC solved so far: 2 (including a Hard One!)

                          V Offline
                          V Offline
                          vtchris peterson
                          wrote on last edited by
                          #13

                          I guess this is a case where programming is subjective. I actually prefer your Lookup2 implementation. I agree that one should not propagate special cases throughout their code, I'm a subscriber to the "say it once" approach; as long as this principle is followed, I'd not complain about either implementation. “The best thing about a boolean is even if you are wrong, you are only off by a bit.” (Anonymous)

                          K 1 Reply Last reply
                          0
                          • V vtchris peterson

                            I guess this is a case where programming is subjective. I actually prefer your Lookup2 implementation. I agree that one should not propagate special cases throughout their code, I'm a subscriber to the "say it once" approach; as long as this principle is followed, I'd not complain about either implementation. “The best thing about a boolean is even if you are wrong, you are only off by a bit.” (Anonymous)

                            K Offline
                            K Offline
                            Keith Barrow
                            wrote on last edited by
                            #14

                            I think that I didn't explain myself properly last night (my previous message was posted after midnight, so hopefully I get some slack :-) !) in my code sample. Lookup(int foo) isn't needed, as lookup[foo] can be called inline, whereas Lookup2(int& foo) would have to be implemented at best. Also, internally Lookup(int foo) is one line of code whereas Lookup2(int& foo) has 3 AND a branching if statement (increasing cyclomatic complexity), both of these factors make my developer's Spider-senses tingle. I agree this is subjective, as I have said in previous posts, there are good arguments for and against the nullable types we are discussing. (I was in the pro-camp for a fair while).

                            CCC solved so far: 2 (including a Hard One!)

                            V 1 Reply Last reply
                            0
                            • M Mycroft Holmes

                              My biggest issue is that when you aggregate a field in SQL you need to deal with the potential null values, you end up with IsNull(Field,0) all over the place just to deal with them. I often put in a default of 0.

                              K Offline
                              K Offline
                              Keith Barrow
                              wrote on last edited by
                              #15

                              I agree wholeheartedly, this is the crux of the problem. The resultant cleaner code is a largeish benefit.

                              CCC solved so far: 2 (including a Hard One!)

                              1 Reply Last reply
                              0
                              • K Keith Barrow

                                I think that I didn't explain myself properly last night (my previous message was posted after midnight, so hopefully I get some slack :-) !) in my code sample. Lookup(int foo) isn't needed, as lookup[foo] can be called inline, whereas Lookup2(int& foo) would have to be implemented at best. Also, internally Lookup(int foo) is one line of code whereas Lookup2(int& foo) has 3 AND a branching if statement (increasing cyclomatic complexity), both of these factors make my developer's Spider-senses tingle. I agree this is subjective, as I have said in previous posts, there are good arguments for and against the nullable types we are discussing. (I was in the pro-camp for a fair while).

                                CCC solved so far: 2 (including a Hard One!)

                                V Offline
                                V Offline
                                vtchris peterson
                                wrote on last edited by
                                #16

                                You did a lot better job explaining yourself this time :) Another appropriate use of nullables can be seen in a recent post: Using LINQ to Calculate Basic Statistics[^] Here, null is used as a return for standard deviation if the set to calculate is invalid (e.g. null, empty, or < 2 elements). I think I tend to like that better than an out parameter and a boolean return value, and is certainly preferable to returning a valid double in an error case. I guess one could argue that a negative value would be ok (since std dev is >= 0), or an exception should be raised... “To err is human, but to really foul things up you need a computer.” -Paul Ehrlich

                                K 1 Reply Last reply
                                0
                                • V vtchris peterson

                                  You did a lot better job explaining yourself this time :) Another appropriate use of nullables can be seen in a recent post: Using LINQ to Calculate Basic Statistics[^] Here, null is used as a return for standard deviation if the set to calculate is invalid (e.g. null, empty, or < 2 elements). I think I tend to like that better than an out parameter and a boolean return value, and is certainly preferable to returning a valid double in an error case. I guess one could argue that a negative value would be ok (since std dev is >= 0), or an exception should be raised... “To err is human, but to really foul things up you need a computer.” -Paul Ehrlich

                                  K Offline
                                  K Offline
                                  Keith Barrow
                                  wrote on last edited by
                                  #17

                                  vtpdawg wrote:

                                  Here, null is used as a return for standard deviation if the set to calculate is invalid (e.g. null, empty, or < 2 elements).

                                  The Mode method, this could be a valid use of null as a set like {1,2,3,4} doesn't have a single modal value (unlike {1,1,2,3,4}. Null isn't "zero" or an empty string or somesuch, it really denotes the abscence of anything. Though equally could implement the Method so that it throws an exception if the set doesn't have a mode. The author of the article states that he returns null as this is what Excel does. You pays your money, you takes your choice on this I think.

                                  vtpdawg wrote:

                                  Here, null is used as a return for standard deviation if the set to calculate is invalid (e.g. null, empty, or < 2 elements).

                                  This is a different matter, the code definately should throw an error, as you can't perform SD calcs on such sets. I know that Exceptions ring alarm bells as the perception is that they have bad performance. This is indeed true if a debug build is made, however when a live build is made the performance is close to events (which is, after all what they are underneath).

                                  vtpdawg wrote:

                                  I think I tend to like that better than an out parameter and a boolean return value, and is certainly preferable to returning a valid double in an error case.

                                  Agreed, that would be an ugly solution, and as I have [hopefully successfuly] explained an unecessary one as it can be handled via exception.

                                  CCC solved so far: 2 (including a Hard One!)

                                  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