PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2017 [RESOLVED] Difference between Null, Nothing and ""-VBForums
Results 1 to 25 of 25

Thread: [RESOLVED] Difference between Null, Nothing and ""

  1. #1

    Thread Starter
    Addicted Member Slabs1960's Avatar
    Join Date
    Mar 2017
    Location
    Oranjemund, Namibia
    Posts
    173

    Resolved [RESOLVED] Difference between Null, Nothing and ""

    Trying to understand the subtle differences, if any, between Null, Nothing and "". When do you use which one or do you test for all?
    I can fix what stupid does, but, I cannot fix stupid

  2. #2
    Hyperactive Member AceDuk's Avatar
    Join Date
    Jan 2016
    Location
    Macedonia
    Posts
    465

    Re: Difference between Null, Nothing and ""

    Code:
    Dim s As String = vbNull
    No object exists, but the variable s that references a string object does exist, but it references nothing.
    Code:
    Dim s As String = Nothing
    What do you have? You have a declared variable called s but it has literally no value - it is nothing more than a placeholder for where a value could go. If you attempt to use this at this point you will get a null reference exception because that's what this is: A null reference. Now let's assume you have this:
    Code:
    Dim s As String = ""
    What you now have is a defined variable which actually has a value. An empty string may not mean much but it is an actual value so you would no longer get a null reference exception if you tried to use it because it isn't a null reference: It is a reference to a valid value.
    Please Mark your Thread "Resolved", if the problem is solved & Rate those who have helped you

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    In VB.NET any variable is Nothing by default. If you declare a variable and don't assign a value to it then it will be Nothing. The memory location containing the variable literally contains zero, but what that means depends on the data type. For reference types, which basically means classes, it means that the variable refers to no object. For value types, which basically means structures, it depends on the type. For numeric types, it means the number zero. For DateTime, it means #1/01/0001#. For Boolean, it means False. For complex structures, it means that each field will have its default value.

    The fact that you have mentioned "" seems to suggest that you're interested in Strings specifically. "" is an empty String, so it's only relevant when dealing with Strings. It is better practice to use String.Empty in VB.NET. In the case of a String variable, it can either be Nothing or it can refer to a String object. If it refers to an object, that String can contain zero, one or more characters. A String with zero characters is still a String object, just as zero is still a value for numeric types.

    Sometimes people use Nothing and String.Empty interchangeably, but you generally shouldn't. You should use Nothing whether there is logically no value and you should use String.Empty when there is logically a value that contains no characters. If you want to treat Nothing and String.Empty the same way then you can use the String.IsNullOrEmpty method to detect either. If you want to treat Strings containing only whitespace the same way too, use String.IsNullOrWhitespace.

    Note that when comparing Strings, you are usually interested in value equality, i.e. whether two Strings contain the same characters, rather than reference equality, i.e. whether two variables refer to the same object. If you're looking for Nothing specifically though, you should use reference equality, because you want to know whether the variable refers to no object. If you use 'If myString Is Nothing Then' then you will detect only a null reference. If you use 'If myString = Nothing Then' then you will be doing the same as using String.IsNullOrEmpty.

    As for Null it depends what you are actually referring to. My guess is that you are talking about data from a database. ADO.NET doesn't use Nothing to represent database nulls because it wouldn't work for value types. If you retrieve nulls from a database using ADO.NET then you will get instances of the DBNull class, specifically the DBNull.Value field. If you're working with ADO.NET and you want to test for null then you look for DBNull.Value. DataRows and data readers have their own methods for detecting nulls, i.e. IsNull and IsDBNull respectively, so you should use those. Otherwise, you might do this:
    vb.net Code:
    1. If myDatabaseValue Is DBNull.Value Then

  4. #4
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: Difference between Null, Nothing and ""

    There's not a good way to make this not confusing.

    Nothing is not null, but sometimes it behaves sort of like null. This is very complex, and as much as I like to make fun of places where VB is complex, there just isn't a good way to accomplish what they wanted on top of .NET.

    To understand it, you REALLY need to be comfortable with what the words "reference semantics" and "value semantics" mean.

    Think about apples. A big, fat, barrel of apples. Sometimes I just say, "I want to eat an apple". You can take any apple out of the barrel of apples and I'll eat it. You might hold up two of the apples and ask me, "Are these apples the same?" In this case, I'll probably say, "Yes", because all I care is that they aren't rotten. That's what "value semantics" means. It means I might compare two different things and decide that they are "the same" for my purposes.

    Now imagine I have a machine that can magically duplicate apples. You give me an apple, and I duplicate it. They look, taste, and smell exactly the same. They are the same color, weigh the same, and have marks in the same places. You ask me, "Are these the same apple?", and I say, "No". This is still true! Even though they are identical in almost every way, they are still two different apples. This is "reference semantics", where we are only concerned with, "Am I talking about the same object?", and if there are two of them they're never "the same".

    In VB .NET, "Nothing" behaves like 'null' in the context of reference semantics. It behaves differently in the context of value semantics.

    For reference semantics, we're talking about Class types like Form. If you declare the variable without giving it a value, it is automatically assigned Nothing to indicate, "This is an unassigned variable".
    Code:
    Dim unassigned As Form ' = Nothing
    If you try to do anything with that variable but assign it a value, you get a NullReferenceException. It is often wrong to try to compare it to Nothing with value semantics:
    Code:
    If unassigned = Nothing Then
    This usually fails because a lot of reference types don't define how "=" works. It also makes little logical sense: unassigned values don't really equal anything, so comparing them even to Nothing is weird. It's more appropriate to use Is:
    Code:
    If unassigned Is Nothing Then
    For value semantics, we're talking about Structure types like and DateTime. But it can also include Class types like String, if the implementor goes out of their way and, specifically for String, using some compiler magic.

    Value types cannot be assigned Nothing as a value. They HAVE to exist. When you compare them to Nothing, the language designers decided to treat Nothing as "the default value for the type". So for Integers, Nothing is more or less the same as 0, even though you can't ever really assign Nothing to an Integer variable:
    Code:
    Dim foo As Integer
    Console.WriteLine(foo = Nothing) ' True
    
    foo = 0
    Console.WriteLine(foo = Nothing) ' True
    Two things are interesting there. First, I used "=" and not "Is". The "Is" operator only works on reference types. Value types are supposed to provide an "=" implementation. Because "Nothing" isn't a valid value, it gets converted to the default value for the type when I perform the comparison. I wouldn't rely on this. It's all-around smarter to just not involve Nothing when working with value types.

    String gets special consideration. It's a Class type, but has special consideration in the compiler to make it have value semantics. That leads to some really weird behaviors that make it even harder to understand just what Nothing means:
    Code:
    Dim foo As String = ""
    Console.WriteLine(foo Is Nothing) ' False
    Console.WriteLine(foo = Nothing)  ' True
    Console.WriteLine(foo.Length)     ' 0
    
    foo = Nothing
    Console.WriteLine(foo Is Nothing) ' True
    Console.WriteLine(foo = Nothing)  ' True
    Console.WriteLine(foo.Length)     ' NullReferenceException
    That's why understanding reference and value semantics is so important. What's happening here:
    • When you make a comparison with "Is", you are asking, "Does this string represent an unassigned variable?" This is reference semantics. "" is not the same thing as "unassigned", so it's false if the string is "".
    • When you make a comparison with "=", you are asking, "Is this the same value as Nothing?" The VB language has a special rule that Nothing is considered equal, with value semantics, to the empty string. So in this case, the string "is not Nothing", but "has the same value as Nothing". It's still illegal to use the String's methods and properties, because "having the same value as Nothing" is not the same thing as "being nothing".


    Generally, you don't have to think about it that deeply, but every now and then it comes up.

    In short: Nothing is usually serving the same purpose as null. But you can tweak things to make it behave differently. Some of this is because of quirks of VB, but C# has the same difference in reference/value semantics and still has many of these confusing situations.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,224

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Sitten Spynne View Post
    There's not a good way to make this not confusing.
    I have nothing to add to those last two posts, but I do REALLY want to emphasize this one point from what Sitten wrote. Strings are reference types that behave like value types, and nothing is much more confusing than that.
    My usual boring signature: Nothing

  6. #6

    Thread Starter
    Addicted Member Slabs1960's Avatar
    Join Date
    Mar 2017
    Location
    Oranjemund, Namibia
    Posts
    173

    Re: Difference between Null, Nothing and ""

    The reason I asked the question was because of this. The following works but every thing else does not. (With relation to combobox on a DGV)

    DGVConfigurationFile.Rows(r).Cells("cfgCluster").Value = Nothing
    Great answers. I have a better understanding, I hope
    I can fix what stupid does, but, I cannot fix stupid

  7. #7

    Thread Starter
    Addicted Member Slabs1960's Avatar
    Join Date
    Mar 2017
    Location
    Oranjemund, Namibia
    Posts
    173

    Re: Difference between Null, Nothing and ""

    On a related note, I noticed:
    DGVConfigurationFile.Rows(r).Cells("cfgCluster").Value
    returns nothing if not assigned.


    DGVConfigurationFile.Rows(r).Cells("cfgCluster").Value.ToString
    returns ""
    I can fix what stupid does, but, I cannot fix stupid

  8. #8
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Shaggy Hiker View Post
    I have nothing to add to those last two posts, but I do REALLY want to emphasize this one point from what Sitten wrote. Strings are reference types that behave like value types, and nothing is much more confusing than that.
    They actually don't. This is a common misconception, probably as a result of the fact that String comparisons are usually done for value equality rather than reference equality and also because Strings are immutable. Strings are reference types and they behave exactly like other reference types.

  9. #9
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Slabs1960 View Post
    The reason I asked the question was because of this. The following works but every thing else does not. (With relation to combobox on a DGV)


    Great answers. I have a better understanding, I hope
    If that's the reason that you asked the question then it probably would have been a good idea to say that in your first post. If we know why you're asking a question then we can tailor our answers to that.

  10. #10
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Slabs1960 View Post
    On a related note, I noticed:
    returns nothing if not assigned.


    returns ""
    That's wrong. Like I said, every variable is Nothing by default. If you don't assign anything to the Value of a DataGridViewCell then the underlying variable will be Nothing and thus the Value property will return Nothing. If that is the case though, your second code snippet would throw a NullReferenceException. You cannot access any member of Nothing because there's no object, so calling ToString is not valid. If, on the other hand, you had retrieved the data from a database and that field was null in that database then the Value of the cell would be DBNull.Value and that would indeed cause ToString to return an empty String. There's no way that both those code snippets can work as you described for the same data.

  11. #11
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jmcilhinney View Post
    They actually don't. This is a common misconception, probably as a result of the fact that String comparisons are usually done for value equality rather than reference equality and also because Strings are immutable. Strings are reference types and they behave exactly like other reference types.
    You forgot about Interning. Try to recreate this scenario with any other reference type:
    Code:
    Dim firstInstance As String = "Hello"
    Dim secondInstance As String = "Hello"
    Dim thirdInstance As String = "HELLO".ToLower()
    		
    Console.WriteLine(Object.ReferenceEquals(firstInstance, secondInstance))
    Console.WriteLine(Object.ReferenceEquals(firstInstance, thirdInstance))
    Strings are goofy as heck.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  12. #12
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Sitten Spynne View Post
    You forgot about Interning. Try to recreate this scenario with any other reference type:
    Code:
    Dim firstInstance As String = "Hello"
    Dim secondInstance As String = "Hello"
    Dim thirdInstance As String = "HELLO".ToLower()
    		
    Console.WriteLine(Object.ReferenceEquals(firstInstance, secondInstance))
    Console.WriteLine(Object.ReferenceEquals(firstInstance, thirdInstance))
    Strings are goofy as heck.
    That's a fair point to a degree, but the fact that no other reference type has literal support built into the language means that that's not really a fair comparison. What you're demonstrating happens only with literals. Try this code to see that:
    vb.net Code:
    1. Dim s1 = "Hello"
    2. Dim s2 = "Hello"
    3. Dim s3 = "Hel" & "lo"
    4. Dim s4 = "Hel"
    5. Dim s5 = "lo"
    6. Dim s6 = s4 & s5
    7.  
    8. Console.WriteLine((s1 Is s2))
    9. Console.WriteLine((s1 Is s3))
    10. Console.WriteLine((s1 Is s6))
    Also, the fact that you can do something with String references doesn't mean that Strings behave like value types because you can't do anything with value type references. Also, while I guess it depends on your perspective, I don't really think that it is goofy as heck to try to make use of Strings, which is extremely common, more efficient in that way when reference equality between Strings is basically irrelevant. You'd only be tripped up by that behaviour if you're doing something that you almost certainly shouldn't be doing in the first place.

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    34,224

    Re: Difference between Null, Nothing and ""

    What makes strings goofy is the way they behave for somebody starting out. If you come fresh to .NET, you will soon enough hear about value types and reference types, and how each one works. You will also read that a string is a reference type....but they you start using it, and it acts a whole lot like a value type. That's what makes it confusing. The fact that it is consistent to people who know the language well is irrelevant to the confusion induced in somebody coming new to the language. After all, nobody new is going to be thinking about references to value types, though that would show that strings really aren't value types.

    However, let me also add that I'm not unhappy with this situation. Default types cause confusion, and they don't need to. Strings can cause confusion, but we clearly all benefit from the way they behave, so the confusion is well worth it.
    My usual boring signature: Nothing

  14. #14
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: Difference between Null, Nothing and ""

    Well, the truth is more complex. It only happens automatically with literals, but you can manually participate. That conversation's getting into the weeds, though.

    The points I want to stick to are:
    • It's easy to explain how value types work: they can never be Nothing, so even when uninitialized they have some default value.
    • It's easy to explain VB's additions to that: for value comparisons, "Nothing" is automatically considered to mean "the default value for this type".
    • It's easy to explain how reference types work: uninitialized variables are Nothing and you can also manually assign Nothing to a variable.
    • Nothing for reference types behaves like the concept of 'null', and there's no concept of a "default value" that Nothing can be compared to (unless the type goes out of its way to overload the comparison operators.)
    • String is a reference type implemented with strong value semantics, which is hard to do and uncommon. VB extends Nothing's behavior to make it the only reference type that ALSO gets the value type behavior. This makes String a bad example for demonstrating a lot of reference-type concepts. (But String is a GOOD example for discussion of value semantics!)


    I just noticed I didn't really talk about vbNull or DBNull.

    I don't actually know what vbNull is, but it isn't Nothing. It looks, to me, like it's part of some VB6 compatibility API to help make some VB6 feature that isn't well-supported in .NET still work. I don't think you should use vbNull unless you're using that API.

    Now DBNull, that has a reason!

    Most databases will let any column have a null value. They also tend to let you have a separate concept of the column's default value. So this means their concept of null is different from .NET's Nothing in a few important ways:
    1. Any type, including Integer or DateTime, can be null in most databases.
    2. If the default value for a column is not null, then "null" does not mean the same thing as "unassigned".


    When ADO .NET was designed, .NET wasn't even released yet. We didn't have a concept of a "nullable value type". They needed a way for you to get data of a specific type out of a column. But it also needed to support giving you a null value for types like Integer. That's a problem, because a function that returns Integer can't return Nothing. And even if it could, since operators like Is only support reference types, you couldn't easily tell the difference between "the value is 0" or "the value is being reported as 0 because it is actually Nothing".

    DBNull solves this problem. It is a special object that is returned from functions that can return objects, and it serves to distinguish between "this column has its default value" and "this column is null". So if you call a function like IDataReader.GetValue(), you have to check before any conversions to see if the value you got is DBNull:
    Code:
    Dim rawCustomerId As Object = reader.GetValue(0)
    If rawCustomerId.Equals(DbNull.Value) Then
        ' Null!
    Else
        Dim customerId As Integer = CInt(rawCustomerId)
        ...
    End If
    Alternatively, many of these APIs have strongly-typed calls that will throw an exception if you call them when DBNull is present and can't be returned. In those cases, there's some other way to tell if the column is null:
    Code:
    If reader.IsDbNull(0) Then
        ' Null!
    Else
        Dim customerId As Integer = reader.GetInt32(0)
        ...
    So DbNull and Nothing are different concepts. DbNull exists to represent how databases tend to treat null in a way that .NET can't represent with Nothing. It's an object that means null, if that makes any sense. We have a way to represent this situation now with nullable types, but they came many years after ADO .NET was designed and, for technical reasons, can't be patched in without doing some things that might make it even more confusing.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  15. #15
    PowerPoster jcis's Avatar
    Join Date
    Jan 2003
    Location
    Argentina
    Posts
    4,423

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Sitten Spynne View Post
    You forgot about Interning. Try to recreate this scenario with any other reference type:
    Code:
    Dim firstInstance As String = "Hello"
    Dim secondInstance As String = "Hello"
    '..
    Console.WriteLine(Object.ReferenceEquals(firstInstance, secondInstance)) ' = True
    '..
    It looks to me that, when using literals, ReferenceEquals and IS are lying to us. ReferenceEquals returns True when both are not the same instance, if they were, by changing firstInstance value, secondInstance value should also change, that's what should happen with two equal references (pointers) that point to the same place in memory. It seems that using literals on Strings make ReferenceEquals (and also IS) to work like an EQUAL sign (=), by using the String object's values and not their references. Quite crazy but not a problem at all, as it's been said, we'll never need to play with this at all.

  16. #16

    Thread Starter
    Addicted Member Slabs1960's Avatar
    Join Date
    Mar 2017
    Location
    Oranjemund, Namibia
    Posts
    173

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jmcilhinney View Post
    If that's the reason that you asked the question then it probably would have been a good idea to say that in your first post. If we know why you're asking a question then we can tailor our answers to that.
    The reason I did not ask a question is that I had working code and want to have a better understanding of the concept. Not an answer to a specific question.

    Reading the replies to this thread is much more educational than any book .

    Remember I am teaching myself by coding. When coding something I try something if it works, great. If not, read search the internet until I find something that does. Once I have working code, I wonder if it is spaghetti code, or the correct way. I then post a thread like this.

    I read each reply several times. I also come back to them as they contain a lot of information and concepts that are new to me.
    Last edited by Slabs1960; Jul 4th, 2017 at 03:01 PM.
    I can fix what stupid does, but, I cannot fix stupid

  17. #17
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jcis View Post
    It looks to me that, when using literals, ReferenceEquals and IS are lying to us. ReferenceEquals returns True when both are not the same instance, if they were, by changing firstInstance value, secondInstance value should also change, that's what should happen with two equal references (pointers) that point to the same place in memory. It seems that using literals on Strings make ReferenceEquals (and also IS) to work like an EQUAL sign (=), by using the String object's values and not their references. Quite crazy but not a problem at all, as it's been said, we'll never need to play with this at all.
    Nope. ReferenceEquals and 'Is' are telling it like it is. In that code, ReferenceEquals returns True because of interning, i.e. two literals with the same value will only result in one String object, thus both variables refer to the same object. String objects are immutable though, so you cannot change the object referred to by the variables. All you can do is assign a different object. If you assign a different object to one of the variables, why would you expect that to affect the other variable? The other variable should - and does - continue to refer to the original object.

    Other than the interning part, that's exactly how every reference type works. If you have two variables of any reference type and you assign a different object to one of the variables, the second variable still refers to the original object. You seem to be confusing making a change to a property of the one object that both variables refer to with making one variable refer to a different object. The former is not possible with Strings because they are immutable.

  18. #18
    You don't want to know.
    Join Date
    Aug 2010
    Posts
    4,580

    Re: Difference between Null, Nothing and ""

    What happened there is pretty simple but not obvious. I was trying to point out how weird strings can seem, but I guess I should've also explained why that code isn't broken.

    .NET has a special data structure for storing instances of Strings. To put one inside this structure is to "intern" it. It's supposed to provide some memory/performance benefits in programs that use a lot of String literals, and I've never really seen a good explanation of when you might want to use it yourself (the API is accessible!) This is ONLY for Strings, no other type (publicly) uses this feature.

    When a String is interned, .NET uses one instance even though technically you would expect two instances. This happens behind the scenes, you don't have to think about it.

    The compiler will automatically intern all string literals in your program. "Literals" are the strings you type out. It will not automatically intern strings that are calculated. So to revisit my example:
    Code:
    Dim s1 As String = "Hello"
    Dim s2 As String = "Hello"
    These two String variables are assigned the same literal. So even though logically there should be two different objects with the same value, because of the interning feature this creates two variables referencing the same object.

    Code:
    Dim s3 As String = "H" & "ello"
    This isn't really a literal. The compiler could probably optimize it to one, but that probably happens later than when it decides to do interning. So it doesn't get interned. This String has the same value as the object s1 and s2 reference, but it will be a different object.

    I could use the API methods to show how to make s3 be the same object, but it really doesn't matter. I've never seen a person explain a scenario where manually interacting with String interning yielded any benefits.

    But I swear one time I had a Dictionary-like data structure that was completely ruined by String interning. I had to special-case some code to do something different for Strings. That was a long time ago, and I'd like to forget that project.
    This answer is wrong. You should be using TableAdapter and Dictionaries instead.

  19. #19
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Sitten Spynne View Post
    Code:
    Dim s3 As String = "H" & "ello"
    This isn't really a literal. The compiler could probably optimize it to one, but that probably happens later than when it decides to do interning. So it doesn't get interned. This String has the same value as the object s1 and s2 reference, but it will be a different object.
    That part is wrong. Check out the code in post #12 for a demonstration of that. The compiler does optimise that, even in DEBUG, and it does do so before interning, which happens at run time.

  20. #20
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by Sitten Spynne View Post
    But I swear one time I had a Dictionary-like data structure that was completely ruined by String interning. I had to special-case some code to do something different for Strings. That was a long time ago, and I'd like to forget that project.
    I would guess that that was because you were using reference equality in most cases but had to use value equality for Strings. I would suggest that you would need to create a special case for Strings then anyway, given that value equality is what's relevant in that case. I can't think of a situation where reference equality would be relevant for Strings and it could only be valid if all instances were guaranteed to contain a unique series of characters. That said, if you use the Equals method of reference type objects to compare then Strings will automatically use value equality because that's how String.Equals is implemented.

    This does bring up an interesting point though. I think that it's the case that Strings appear to behave like a value type on the surface (I thought so too at one point, before I looked a bit deeper) because they ideally would be value types because it's their value that is relevant. Char is a value type. The issue is that Strings can be quite big and are used so commonly that they could end up being copied over and over if they were value type objects. String had to be a reference type for it to be efficient but supports literals and has other optimisations that make using it much the same as using a value type. They were both pragmatic choices.

  21. #21
    PowerPoster jcis's Avatar
    Join Date
    Jan 2003
    Location
    Argentina
    Posts
    4,423

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jmcilhinney View Post
    Other than the interning part, that's exactly how every reference type works. If you have two variables of any reference type and you assign a different object to one of the variables, the second variable still refers to the original object. You seem to be confusing making a change to a property of the one object that both variables refer to with making one variable refer to a different object. The former is not possible with Strings because they are immutable.
    Well If ReferenceEquals(,) return True (the case we're talking about) then yes, I'm assuming that both object variables reference the same object (same place in memory) and off course i would expect that making a change in the value of one of them would also affect the other.
    Last edited by jcis; Jul 5th, 2017 at 02:48 PM.

  22. #22
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jcis View Post
    i would expect that making a change in the value of one of them would also affect the other.
    But you CAN'T make a change to the value of one of them. They're Strings. Strings are immutable. Immutable means that you can't make a change to their value. That's why any method that manipulates a String, e.g. String.Replace, returns a new String object rather than modifying the existing String. What you would expect to happen when doing something that is impossible to do is moot.

  23. #23
    Frenzied Member jdc20181's Avatar
    Join Date
    Oct 2015
    Location
    Indiana
    Posts
    1,133

    Re: Difference between Null, Nothing and ""

    Nothing is essentially the vb.net version of NULL

    I think, pretty much, vb.net compiles "" as Nothing just without you specifying, for an example,If you clear select string lets say its the entire thing, then you can say nothing instead of just ""

    Example:

    Code:
        My.Computer.Clipboard.Clear()
            If TextBox1.SelectionLength > 0 Then
                My.Computer.Clipboard.SetText(TextBox1.SelectedText)
    
            End If
            TextBox1.SelectedText = Nothing
        End Sub
    V.s.



    Code:
        My.Computer.Clipboard.Clear()
            If TextBox1.SelectionLength > 0 Then
                My.Computer.Clipboard.SetText(TextBox1.SelectedText)
    
            End If
            TextBox1.SelectedText = ""
        End Sub
    Disclaimer: When code is given for example - it is merely a example.
    See my browser project BeffsBrowser
    Try my new Browser project LightBrowse "A Browser and not much else" Screen Capture with Imgur API


    Unless said otherwise (e.g. From one of my projects thus, those are mostly licensed under MIT) - All Code snippets advice or otherwise that I post on this site, are expressly licensed under Creative Commons Attribution 4.0 International Please respect my copyrights.

  24. #24
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    103,305

    Re: Difference between Null, Nothing and ""

    Quote Originally Posted by jdc20181 View Post
    I think, pretty much, vb.net compiles "" as Nothing just without you specifying, for an example,If you clear select string lets say its the entire thing, then you can say nothing instead of just ""
    That's not true. An empty String is compiled as an empty String and Nothing is compiled as Nothing. They are two different things. What might be confusing you is that Nothing is converted to an empty String for the purposes of comparison by value. Comparison by value is done using the '=' operator while comparison by reference is done using the 'Is' operator. Run this code to see what the implications of that are:
    vb.net Code:
    1. Dim s1 As String
    2. Dim s2 = CStr(Nothing)
    3. Dim s3 = String.Empty
    4. Dim s4 = ""
    5.  
    6. Console.WriteLine(s1 Is Nothing)
    7. Console.WriteLine(s1 = Nothing)
    8. Console.WriteLine(s1 Is String.Empty)
    9. Console.WriteLine(s1 = String.Empty)
    10. Console.WriteLine()
    11. Console.WriteLine(s2 Is Nothing)
    12. Console.WriteLine(s2 = Nothing)
    13. Console.WriteLine(s2 Is String.Empty)
    14. Console.WriteLine(s2 = String.Empty)
    15. Console.WriteLine()
    16. Console.WriteLine(s3 Is Nothing)
    17. Console.WriteLine(s3 = Nothing)
    18. Console.WriteLine(s3 Is String.Empty)
    19. Console.WriteLine(s3 = String.Empty)
    20. Console.WriteLine()
    21. Console.WriteLine(s4 Is Nothing)
    22. Console.WriteLine(s4 = Nothing)
    23. Console.WriteLine(s4 Is String.Empty)
    24. Console.WriteLine(s4 = String.Empty)
    25. Console.ReadLine()
    That code demonstrates that if a String variable is not assigned a value or is explicitly set to Nothing then it is equal to Nothing by both reference and value but it is only equal to an empty String by value and not by reference. On the other hand, if a String variable is set to an empty String then it is equal to an empty String by both reference and value but it is only equal to Nothing by value and not by reference.

  25. #25

    Thread Starter
    Addicted Member Slabs1960's Avatar
    Join Date
    Mar 2017
    Location
    Oranjemund, Namibia
    Posts
    173

    Re: Difference between Null, Nothing and ""

    Thanks for the great answers. I learnt a lot.
    I can fix what stupid does, but, I cannot fix stupid

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width