|
web
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Is there a difference between passing "" and passing Nothing to a Windows API ?Now I'm wondering if that best for String variables - is "" better? With Nothing I assume no memory is set aside nor GC'ed But with "" it is - correct? The system seems to handle a null the same as "". For example: s=A & "more text" 'Works the same if A=Nothing or A="" Does this run the same code? What about passing to a Windows API? Is there a difference between passing "" and passing Nothing? Thank you > Is there a difference between passing "" and passing Nothing? They are different. The simplest example of the difference is withi = Len(s) i = s.Length s.Length will fail if s is nothing. Some vb string handling will work fine (and identically) with "" and nothing. Generally, vb legacy string handling copes with both, but object oriented functionality treats them differently. FYI, my habit is to avoid Nothing with strings.
Show quote
Hide quote
"AMercer" <AMer***@discussions.microsoft.com> wrote in message I going to make this my habit too. No reason not to - except with Windows news:5C395B35-A0FB-4200-AF2E-DFE7EB44B58E@microsoft.com... >> Is there a difference between passing "" and passing Nothing? > > They are different. The simplest example of the difference is with > i = Len(s) > i = s.Length > s.Length will fail if s is nothing. Some vb string handling will work > fine > (and identically) with "" and nothing. Generally, vb legacy string > handling > copes with both, but object oriented functionality treats them > differently. > FYI, my habit is to avoid Nothing with strings. Api calls. Thanks it is considered good coding practice to initialize string values with a
empty string value dim x as string ="" or dim x as string=string.empty if you do not do this you should always use this if not x is nothing then ' must check for nothing before processing end if regards Michel Posseth [MCP] Show quoteHide quote " academic" <acade***@a-znet.com> schreef in bericht news:eTCTLL%23LGHA.500@TK2MSFTNGP15.phx.gbl... > When I declare a reference variable I initialize it to Nothing. > > Now I'm wondering if that best for String variables - is "" better? > > With Nothing I assume no memory is set aside nor GC'ed > > But with "" it is - correct? > > The system seems to handle a null the same as "". > > For example: > > s=A & "more text" 'Works the same if A=Nothing or A="" > > Does this run the same code? > > What about passing to a Windows API? > > Is there a difference between passing "" and passing Nothing? > > > Thank you > > > > > > > > > > >it is considered good coding practice to initialize string values with a It is? I would only do so if I had a good reason for it, not so I>empty string value could be lazy and skip proper null checking later on. Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message I wonder why not - is there some reason to use Nothing and then check?news:el6hSOAMGHA.3432@tk2msftngp13.phx.gbl... > >>it is considered good coding practice to initialize string values with a >>empty string value > > It is? I would only do so if I had a good reason for it, not so I > could be lazy and skip proper null checking later on. > > > It is? I would only do so if I had a good reason for it, not so I According to "practical guidelines and best practices for Microsoft Visual > could be lazy and skip proper null checking later on. Basic and Visual C# Developers" so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) Why : Explicit assignment avoids NullReferenceException errors when referencing the string and simplifies code ( because the string doesn`t have to be tested against null ) note : initializing this way points to the only zero length string that is allocated in the string intern heap so it doesn`t waste memory as some developers believe regards Michel Posseth [MCP] Show quoteHide quote "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> schreef in bericht news:el6hSOAMGHA.3432@tk2msftngp13.phx.gbl... > >>it is considered good coding practice to initialize string values with a >>empty string value > > It is? I would only do so if I had a good reason for it, not so I > could be lazy and skip proper null checking later on. > > > Mattias > > -- > Mattias Sjögren [C# MVP] mattias @ mvps.org > http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com > Please reply only to the newsgroup.
Show quote
Hide quote
"m.posseth" <poss***@planet.nl> schrieb: Mhm... That's why I use 'Right', 'Left', 'Len', etc. if I do not want >> It is? I would only do so if I had a good reason for it, not so I >> could be lazy and skip proper null checking later on. > > According to "practical guidelines and best practices for Microsoft > Visual Basic and Visual C# Developers" > > so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) > > Why : > > Explicit assignment avoids NullReferenceException errors when referencing > the string and simplifies code ( because the string doesn`t have to be > tested against null ) exceptions to be thrown on string variables referencing 'Nothing'. BTW: I do not think that initializing string variables to an empty (zero-length) string is good practice too. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> > Mhm... That's why I use 'Right', 'Left', 'Len', etc. if I do not want I did exactly that for the obvious same reassons ,,,> exceptions to be thrown on string variables referencing 'Nothing'. however i have recently changed my coding style > BTW: I do not think that initializing string variables to an empty We live in a free country ( well ,, i know you and i do :-) ) so you > (zero-length) string is good practice too. can always do as you please however fact is that this book is written by the author of all the programming microsoft visual basic core references ( 6 , 2002, 2003 and the 2005 versions ) and this is a MS press book ( i was also surprised i must admit but it is verry clear in it , and after reading the explanation i am on there side with my coding style ) . i am curious why you think it is not good coding practice Show quoteHide quote "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> schreef in bericht news:%23ObDjZAMGHA.1424@TK2MSFTNGP12.phx.gbl... > "m.posseth" <poss***@planet.nl> schrieb: >>> It is? I would only do so if I had a good reason for it, not so I >>> could be lazy and skip proper null checking later on. >> >> According to "practical guidelines and best practices for Microsoft >> Visual Basic and Visual C# Developers" >> >> so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) >> >> Why : >> >> Explicit assignment avoids NullReferenceException errors when referencing >> the string and simplifies code ( because the string doesn`t have to be >> tested against null ) > > Mhm... That's why I use 'Right', 'Left', 'Len', etc. if I do not want > exceptions to be thrown on string variables referencing 'Nothing'. > > BTW: I do not think that initializing string variables to an empty > (zero-length) string is good practice too. > > -- > M S Herfried K. Wagner > M V P <URL:http://dotnet.mvps.org/> > V B <URL:http://classicvb.org/petition/> Why isn't it a good practice?
Show quoteHide quote > BTW: I do not think that initializing string variables to an empty > (zero-length) string is good practice too. > > -- > M S Herfried K. Wagner > M V P <URL:http://dotnet.mvps.org/> > V B <URL:http://classicvb.org/petition/> " academic" <acade***@a-znet.com> schrieb: I believe it strongly depends on the situation. IMO it's not a good idea to > Why isn't it a good practice? > >> BTW: I do not think that initializing string variables to an empty >> (zero-length) string is good practice too. propose "initialize strings with an empty string" as a general rule. However, it still may make sense in some cases. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> wrote in message What is the benefit of an uninitialized string? Why is it not a "good idea?" news:ua9IMPCMGHA.3460@TK2MSFTNGP15.phx.gbl... >" academic" <acade***@a-znet.com> schrieb: > I believe it strongly depends on the situation. IMO it's not a good idea > to propose "initialize strings with an empty string" as a general rule. > However, it still may make sense in some cases. I mean... Questions: 1) Are there situations where <Nothing> actually *means* something in your code and your algorithms other than <Empty>? 2) Or are you just relying on VB's intrinsic functions (Len, Left, Mid, etc) and "coercion" to safely deal with the string? If so, how do you justify that?... isn't that the same as using Option-"Loose" "Evil-Type-Coercion?" 3) Is it for performance or memory reasons? "CMM" <cmm@nospam.com> schrieb: Yes! The whole discussion is similar to the 'NULL' vs. zero-length string >> I believe it strongly depends on the situation. IMO it's not a good idea >> to propose "initialize strings with an empty string" as a general rule. >> However, it still may make sense in some cases. > > What is the benefit of an uninitialized string? Why is it not a "good > idea?" I mean... > Questions: > 1) Are there situations where <Nothing> actually *means* something in > your code and your algorithms other than <Empty>? or 'NULL' vs. 0 discussion for databases. A zero-length string is different from a 'Nothing' reference. Inside the .NET Framework's class library they are not treated as equal. > 2) Or are you just relying on VB's intrinsic functions (Len, Left, Mid, VB's functions mostly treat "" and 'Nothing' string references as equal. > etc) and "coercion" to safely deal with the string? This means that 'Len', for example, returns 0 for both a 'Nothing' reference and a zero-length string. In case of a method returning either a 'Nothing' reference or a string of arbitrary length I'd choose 'If Len(s) > 0 Then' over 'If s IsNot Nothing AndAlso s.Length > 0 Then' to check if a string object with length greater than 0 has been returned. > 3) Is it for performance or memory reasons? Performance and memory reasons are not important for me in most cases. I prefer to write semantically clear code instead of performing micro-optimizations. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> > Inside the .NET Framework's class library they are not treated as equal. So why do *you* treat them as if they were?I mean in *your* code and in your *your algorithms* do you explicitely use Nothing to accomplish something or do you just let VB's intrinsic operators or functions interpret it as Empty? In other words, is Nothing treated as Empty everywhere in your code? To me, that's the same exact thing as writing stuff like S = 5 where S is a string... when Option Explicit is Off. That's not "good practice." You really have to justify why you say "...it's not a good idea to 'initialize strings with an empty string' as a general rule." Why isn't it a good idea? I mean, 99% of the time, I expect my strings to be Empty not Nothing. Why not declare them as Empty rather than have VB *coerce* the value??? That's what I'm trying to understand. I'm not saying you're wrong... I'm just saying prima facie it doesn't seem to make sense. "CMM" <cmm@nospam.com> schrieb: No, not in general. Only where the difference is irrelevant. I gave you >> Inside the .NET Framework's class library they are not treated as equal. > > So why do *you* treat them as if they were? the sample when I use the 'Len' function instead of 'String.Length'. That's just one sample. If I want to get the rightmost three characters of a string, I use 'Right' instead of 'String.Substring', because it won't throw an exception if the string reference passed to it is pointing to 'Nothing'. Note that these are not samples of treating 'Nothing' as equal to "". > You really have to justify why you say "...it's not a good idea to \\\> 'initialize strings with an empty string' as a general rule." Why isn't it > a good idea? I mean, 99% of the time, I expect my strings to be Empty not > Nothing. Dim s As String = String.Empty .... s = DoSomething() /// .... initializing 's' is completely useless in the sample above and adds additional initialization overhead. That's why I wrote that it doesn't make sense to initialize /every/ string variable with 'String.Empty' or "" instead of letting VB.NET initialize it with a 'Nothing' reference. > Why not declare them as Empty rather than have VB *coerce* the value??? Initializing variables with a certain value doesn't make sense other code prior to the first read-access assigns a value to the variable. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> > Dim s As String = String.Empty Dim s As String = DoSomething()> ... > s = DoSomething() > /// > > ... initializing 's' is completely useless in the sample above and adds > additional initialization overhead. That's why I wrote that it doesn't > make sense to initialize /every/ string variable with 'String.Empty' or "" is the answer. Seems to me that you're still holding on to the VB.Classic notion of "Declaring" variables at the top of a method rather Instantiating them when you need them in a block so that they're destroyed when the block ends. If Condition Then Dim s As String = DoSomething() 'do work End If The benefits of this coding style are many and hard to explain unless you work in a team or are otherwise mindful of future developers maintaining your software. Curious, do you work in a team or alone? Carlos,
> This is not from the VB notation, it comes from the old days and is based on > Seems to me that you're still holding on to the VB.Classic notion of > "Declaring" variables at the top of a method rather Instantiating them > when you need them in a block so that they're destroyed when the block > ends. > the hardware type programming. If you have to debug using the little bulps on a computer, than you are glad that the data is seperated from the instructions and that you not have to calculate a next program word what is behind x positions of data (or a previous before). I agree completely with you, that this is now without any sense and prefer very much the way you describe. I hope that it is clear what I write? Cor I agree.
It didn't help either that in VB.Classic (B.A.S.I.C. too?) Dim didn't actually do anything (except I guess with arrays)... and it could appear *anywhere* in your code, as long as it appeared just once (which wasn't even really necessary either). s = "hello" Dim s As String worked just fine: Then again I remember when I could type: IFLEN(X$)>0THENPRINT"HELLO" (notice no spaces) on the Commodore and the parser knew EXACTLY what I was doing. The good ol' days. ;-) Show quoteHide quote "Cor Ligthert [MVP]" <notmyfirstn***@planet.nl> wrote in message news:exag2uOMGHA.3712@TK2MSFTNGP10.phx.gbl... > Carlos, > >> >> Seems to me that you're still holding on to the VB.Classic notion of >> "Declaring" variables at the top of a method rather Instantiating them >> when you need them in a block so that they're destroyed when the block >> ends. >> > This is not from the VB notation, it comes from the old days and is based > on the hardware type programming. > > If you have to debug using the little bulps on a computer, than you are > glad that the data is seperated from the instructions and that you not > have to calculate a next program word what is behind x positions of data > (or a previous before). > > I agree completely with you, that this is now without any sense and prefer > very much the way you describe. > > I hope that it is clear what I write? > > Cor > > "CMM" <cmm@nospam.com> schrieb: .... which didn't compile in VB6, neither with 'Option Explicit' nor without > It didn't help either that in VB.Classic (B.A.S.I.C. too?) Dim didn't > actually do anything (except I guess with arrays)... and it could appear > *anywhere* in your code, as long as it appeared just once (which wasn't > even really necessary either). > > s = "hello" > Dim s As String it. > worked just fine: No, it didn't.-- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> I seem to remember it being possible at some version (I didn't say VB6). If
not, I stand corrected. Maybe I was thinking of some other macro or scripting lang in the past. Herfried,
I did not read the whole message just curious where CMM and you where disussing about. However I would never compare a database with computer memory. In a database means a Null field, really nothing which means than as well no disk space. In memory that space will be used for other data in another situation of the method, so there will not be any advantage using it or not. (The memory is not perstistent). Just my thought, Cor "Cor Ligthert [MVP]" <notmyfirstn***@planet.nl> schrieb: 'NULL' in a database means "unknown value". This behavior can be replicated > I did not read the whole message just curious where CMM and you where > disussing about. > > However I would never compare a database with computer memory. > > In a database means a Null field, really nothing which means than as well > no disk space. inside VB.NET in different ways ('Nothing' references, 'Nullable(Of String)'). -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> Herfried,
> It means no value, although what constraints it has to fullfil if there is a > 'NULL' in a database means "unknown value". This behavior can be > replicated inside VB.NET in different ways ('Nothing' references, > 'Nullable(Of String)'). > value is known. Cor " academic" <acade***@a-znet.com> schrieb If it has to be an empty string always, use a constant.> > Why isn't it a good practice? Armin well i am confused now
Francesco and Giuseppe are verry clear in there book, that both are even good "" and string.empty however from a developers perspective i would use "" as it is faster to write as string.empty untill i heard from CMM that the IL produces different code for string.empty or "" strange ..... Michel Show quoteHide quote "Armin Zingler" <az.nospam@freenet.de> schreef in bericht news:OcwEuLHMGHA.2580@TK2MSFTNGP14.phx.gbl... >" academic" <acade***@a-znet.com> schrieb >> >> Why isn't it a good practice? > > > If it has to be an empty string always, use a constant. > > > Armin While the IL does produce different code, I don't think it very much matters
in terms of performance in most situations. If you think "" is easier to read, and easier for you to type, then you should use it. Personally, I'm a quick typer and I actually like String.Empty aesthetically versus "" (which I find to be an eyesore).... But that's a purely subjective thing. "CMM" <cmm@nospam.com> schrieb: I'm curious why the compiler doesn't emit the same IL instruction for "" it > While the IL does produce different code, I don't think it very much > matters in terms of performance in most situations. does for 'String.Empty'. Maybe this will change in a future version as part of a compiler optimization. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> wrote in message They could do it as an optional "optimization" of sorts where the VB news:emREtWJMGHA.3276@TK2MSFTNGP09.phx.gbl... > I'm curious why the compiler doesn't emit the same IL instruction for "" > it does for 'String.Empty'. Maybe this will change in a future version as > part of a compiler optimization. compiler sees "" and replaces it with String.Empty (behind-the-scenes) before compiling. But the reason of "why" is very clear. One is a literal that has to be boxed and turned into an object in order to be used (because that's the way stuff works) and the other is already an object. >One is a literal There's no boxing going on here, string is a reference type.>that has to be boxed and turned into an object in order to be used (because >that's the way stuff works) and the other is already an object. Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message A boxing is an object. That literal in your code isn't.> There's no boxing going on here, string is a reference type. From MSDN: Boxing is the process of converting a literal, like a single space, to the implied object (in this case, a string object) for that literal. >A boxing is an object. That literal in your code isn't. That quote seems to be from an article by Paul Sheriff, and he seems>From MSDN: >Boxing is the process of converting a literal, like a single space, to the >implied object (in this case, a string object) for that literal. to have come up with his own definition of the term boxing. That's unfortunate, because if we don't have a common terminology it gets pretty hard and confusing to discuss things like this. The .NET framework docs have a different definition that I follow: "The conversion of a value type instance to an object, which implies that the instance will carry full type information at run time and will be allocated on the heap." http://msdn2.microsoft.com/en-us/library/b85sw2k8.aspx See, nothing about literals and it specifically says value types. Frankly I don't understand where Mr Sheriff his version from. Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. I guess you'd have to understand what boxing means... semantically I guess.
Without knowledge of what a "value type" really is (a set of bytes-- otherwise known as intrinsic or primitive types) and how a string (an array of bytes) is stored in a table and referenced by an "Object", then you would be confused. Again, that literal "" in your code does not refer to an object. It has to be converted to (boxed? use whatever term you want to use) into an object. Show quoteHide quote "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message news:uUq5n0OMGHA.3408@TK2MSFTNGP12.phx.gbl... > >>A boxing is an object. That literal in your code isn't. >>From MSDN: >>Boxing is the process of converting a literal, like a single space, to the >>implied object (in this case, a string object) for that literal. > > > That quote seems to be from an article by Paul Sheriff, and he seems > to have come up with his own definition of the term boxing. That's > unfortunate, because if we don't have a common terminology it gets > pretty hard and confusing to discuss things like this. > > The .NET framework docs have a different definition that I follow: > > "The conversion of a value type instance to an object, which implies > that the instance will carry full type information at run time and > will be allocated on the heap." > > http://msdn2.microsoft.com/en-us/library/b85sw2k8.aspx > > See, nothing about literals and it specifically says value types. > Frankly I don't understand where Mr Sheriff his version from. > > > Mattias > > -- > Mattias Sjögren [C# MVP] mattias @ mvps.org > http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com > Please reply only to the newsgroup.
Show quote
Hide quote
"m.posseth" <poss***@planet.nl> schrieb I was not referring to "" or string.empty. I wanted to say that it does not> > " academic" <acade***@a-znet.com> schrieb > > > > > > Why isn't it a good practice? > > > > > > If it has to be an empty string always, use a constant. > > > well i am confused now > > > Francesco and Giuseppe are verry clear in there book, that both are > even good > > "" and string.empty > > however from a developers perspective i would use "" as it is > faster to write as string.empty > untill i heard from CMM that the IL produces different code for > string.empty or "" > > strange ..... make sense to initalize a string variable with "" (or string.empty) always, because if it would be a zero length string always, you should better use a constant instead of a variable. Armin Unless you use a Nothing-String to denote some "meaning" other than Empty,
there is no reason to NOT initialize it to Empty. If you really WANT *Nothing* for some reason, then that's a different story. But, if you are just relying on VB's comparison operators and intrinsic functions (Left,Right,Len, etc) to keep you safe and interpret that Nothing-String as Empty, you are for sure treading on shaky ground... and it is for sure a BAD coding practice. Laziness... not initializing a string and relying on VB's hand-holding is the same as using Evil-Type-Coercion that we've all gotten past years ago. Suppose after you leave your company a developer comes along and wants to add a feature that uses one of the classes that you've written.... If HerfriedWagnerAwesomeControl.Title.Length < 10 Then.... doh! EXCEPTION! Sadly, this error might not manifest itself until N point in the future when the app is in Production. Show quoteHide quote "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> wrote in message news:%23ObDjZAMGHA.1424@TK2MSFTNGP12.phx.gbl... > "m.posseth" <poss***@planet.nl> schrieb: >>> It is? I would only do so if I had a good reason for it, not so I >>> could be lazy and skip proper null checking later on. >> >> According to "practical guidelines and best practices for Microsoft >> Visual Basic and Visual C# Developers" >> >> so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) >> >> Why : >> >> Explicit assignment avoids NullReferenceException errors when referencing >> the string and simplifies code ( because the string doesn`t have to be >> tested against null ) > > Mhm... That's why I use 'Right', 'Left', 'Len', etc. if I do not want > exceptions to be thrown on string variables referencing 'Nothing'. > > BTW: I do not think that initializing string variables to an empty > (zero-length) string is good practice too. > > -- > M S Herfried K. Wagner > M V P <URL:http://dotnet.mvps.org/> > V B <URL:http://classicvb.org/petition/> >According to "practical guidelines and best practices for Microsoft Visual Then I guess I'll have to disagree with them, it wouldn't be the first>Basic and Visual C# Developers" > >so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) time. >Explicit assignment avoids NullReferenceException errors when referencing I won't trade correctness for simplicity. Assigning "" to strings by>the string and simplifies code ( because the string doesn`t have to be >tested against null ) default, just to avoid NullReferenceExceptions, feels like a hack that will just hide the actual problem. Exceptions can be good things if they help you find errors during development, suppressing them is taking the easy way out. Do they also recommend catch-all exception handling (or On Error Resume Next style programming)? Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. > I won't trade correctness for simplicity. Assigning "" to strings by Using VB's type emptystring type coercion is more of a hack. The actual > default, just to avoid NullReferenceExceptions, feels like a hack that > will just hide the actual problem. problem is that a string should mean something unless you really need it not to. You don't have to initialize it to "" or String.Empty. You can initialize it when you NEED it as so: Dim s As String = SomeMethod(). What's wrong with that? .... AND even better.... declare it inside blocks (If, Loops, etc) so it goes out of scope at the end of the block. Man, this is just programming 101. If VB developer's are still putting dozens of Dim's at the top of their methods, boy, that doesn't bode well for the future of this platform. Dim in VB.NET is not the same ol' VB.Classic Dim. They're missing out on the whole point. > Exceptions can be good things if Initializing string is not suppressing an exception. Using Len(str) insetad > they help you find errors during development, suppressing them is > taking the easy way out. of str.Length *IS* suppressing it. Fact is, pretty much the entire programming world has settled on the notion that this is good practice. In C++ it's practically a law. In C# it's just a darn good practice. It's only in VB where developers feel free to be super-lazy and write horribly and hard to maintain code if they so wished where this seems to be tolerated. >You can Nothing, I'm glad we finally agree on something. :) But that's not>initialize it when you NEED it as so: Dim s As String = SomeMethod(). What's >wrong with that? what the original poster asked. And I guess people afraid of nulls would still have to follow that line with If s Is Nothing Then s = "" Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message Only if SomeMethod() was an XML or Database IO call.... or if SomeMethod() news:%23X1Gg8OMGHA.3260@TK2MSFTNGP11.phx.gbl... >>You can initialize it when you NEED it as so: Dim s As String = >>SomeMethod(). What's >>wrong with that? > > Nothing, I'm glad we finally agree on something. :) And I guess > people afraid of nulls would still have to follow that line with > If s Is Nothing Then s = "" were in a dependency written by Herfried Wagner (MVP). :-o Otherwise, I'd assume the writers of SomeMethod were good coders. For instance I wouldn't expect a Nothing returned from: Dim s As String = PadMyString(x) where x might equal 0 times. But with Herfried Wagner (maybe yours too?) code... anything is possible! And to reiterate my statement about assumming that dependencies I might be
using were written by "good coders" From MS Guidelines - Array Usage Guidelines (BTW, a string is really an array) Returning Empty Arrays *String* and *Array* properties should never return a null reference. Null can be difficult to understand in this context. For example, a user might assume that the following code will work. .... (obvious code sample) I didn't add the emphasis. They did. Obviously this isn't a "rule." Database IO calls return nulls all the time. These are cases where you expect them... and they serve a particular purpose. But, unless Nothing actually means something in your algorithm OTHER than Empty, do the guys who might have to maintain your code in the future or use your classes as a dependency and please initialize your poor strings. Show quoteHide quote "CMM" <cmm@nospam.com> wrote in message news:%239$MIdQMGHA.3272@tk2msftngp13.phx.gbl... > "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message > news:%23X1Gg8OMGHA.3260@TK2MSFTNGP11.phx.gbl... >>>You can initialize it when you NEED it as so: Dim s As String = >>>SomeMethod(). What's >>>wrong with that? >> >> Nothing, I'm glad we finally agree on something. :) And I guess >> people afraid of nulls would still have to follow that line with >> If s Is Nothing Then s = "" > > Only if SomeMethod() was an XML or Database IO call.... or if SomeMethod() > were in a dependency written by Herfried Wagner (MVP). :-o > > Otherwise, I'd assume the writers of SomeMethod were good coders. For > instance I wouldn't expect a Nothing returned from: > Dim s As String = PadMyString(x) where x might equal 0 times. But with > Herfried Wagner (maybe yours too?) code... anything is possible! > > -- > -C. Moya > www.cmoya.com >
Show quote
Hide quote
"CMM" <cmm@nospam.com> schrieb: I use 'Len' et al. to /intentionally/ suppress the exceptions if this is >> I won't trade correctness for simplicity. Assigning "" to strings by >> default, just to avoid NullReferenceExceptions, feels like a hack that >> will just hide the actual problem. > > Using VB's type emptystring type coercion is more of a hack. The actual > problem is that a string should mean something unless you really need it > not to. You don't have to initialize it to "" or String.Empty. You can > initialize it when you NEED it as so: Dim s As String = SomeMethod(). > What's wrong with that? > ... AND even better.... declare it inside blocks (If, Loops, etc) so it > goes out of scope at the end of the block. Man, this is just programming > 101. > > If VB developer's are still putting dozens of Dim's at the top of their > methods, boy, that doesn't bode well for the future of this platform. Dim > in VB.NET is not the same ol' VB.Classic Dim. They're missing out on the > whole point. > >> Exceptions can be good things if >> they help you find errors during development, suppressing them is >> taking the easy way out. > > Initializing string is not suppressing an exception. Using Len(str) > insetad of str.Length *IS* suppressing it. semantically correct (samples given in previous posts). > Fact is, pretty much the entire programming world has settled on the In VB.NET people write 'If Len(s) > 0 Then' instead of 'if (s != null && > notion that this is good practice. In C++ it's practically a law. In C# > it's just a darn good practice. It's only in VB where developers feel free > to be super-lazy and write horribly and hard to maintain code if they so > wished where this seems to be tolerated. s.Length > 0)' for example. I don't think this is a sign of laziness, instead I consider it an important high-level programming feature which helps simplifying code. BTW: I consider the rule "always assign an empty string to string variables" lazy because it prevents the developer from seeing potential problems. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> > helps simplifying code. BTW: I consider the rule "always assign an empty I don't disagree.... my rule isn't to always initialize a string to Empty. > string to string variables" lazy because it prevents the developer from > seeing potential problems. It's to always initialize it to something when I declare it. I try to declare objects when I need them. You wouldn't see a bunch of Dim's that don't initialize anything at the top my methods. That's VB.Classic mentality. VB.NET's Dim is a whole new creature. Anyhow, please describe "potential problems?" Like what? Give an example. Show quoteHide quote "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> wrote in message news:OngtH9OMGHA.3276@TK2MSFTNGP09.phx.gbl... > "CMM" <cmm@nospam.com> schrieb: >>> I won't trade correctness for simplicity. Assigning "" to strings by >>> default, just to avoid NullReferenceExceptions, feels like a hack that >>> will just hide the actual problem. >> >> Using VB's type emptystring type coercion is more of a hack. The actual >> problem is that a string should mean something unless you really need it >> not to. You don't have to initialize it to "" or String.Empty. You can >> initialize it when you NEED it as so: Dim s As String = SomeMethod(). >> What's wrong with that? >> ... AND even better.... declare it inside blocks (If, Loops, etc) so it >> goes out of scope at the end of the block. Man, this is just programming >> 101. >> >> If VB developer's are still putting dozens of Dim's at the top of their >> methods, boy, that doesn't bode well for the future of this platform. Dim >> in VB.NET is not the same ol' VB.Classic Dim. They're missing out on the >> whole point. >> >>> Exceptions can be good things if >>> they help you find errors during development, suppressing them is >>> taking the easy way out. >> >> Initializing string is not suppressing an exception. Using Len(str) >> insetad of str.Length *IS* suppressing it. > > I use 'Len' et al. to /intentionally/ suppress the exceptions if this is > semantically correct (samples given in previous posts). > >> Fact is, pretty much the entire programming world has settled on the >> notion that this is good practice. In C++ it's practically a law. In C# >> it's just a darn good practice. It's only in VB where developers feel >> free to be super-lazy and write horribly and hard to maintain code if >> they so wished where this seems to be tolerated. > > In VB.NET people write 'If Len(s) > 0 Then' instead of 'if (s != null && > s.Length > 0)' for example. I don't think this is a sign of laziness, > instead I consider it an important high-level programming feature which > helps simplifying code. BTW: I consider the rule "always assign an empty > string to string variables" lazy because it prevents the developer from > seeing potential problems. > > -- > M S Herfried K. Wagner > M V P <URL:http://dotnet.mvps.org/> > V B <URL:http://classicvb.org/petition/> "CMM" <cmm@nospam.com> schrieb im Newsbeitrag Well, I used to declare variables directly in front of their first usage in news:uRy5YYPMGHA.1424@TK2MSFTNGP12.phx.gbl... >> helps simplifying code. BTW: I consider the rule "always assign an >> empty string to string variables" lazy because it prevents the developer >> from seeing potential problems. > > I don't disagree.... my rule isn't to always initialize a string to Empty. > It's to always initialize it to something when I declare it. I try to > declare objects when I need them. You wouldn't see a bunch of Dim's that > don't initialize anything at the top my methods. That's VB.Classic > mentality. VB.NET's Dim is a whole new creature. code even in Classic VB. By doing so, the compiler prevented me from unintentionally assigning a value to the variable before it is actually used in code. > Anyhow, please describe "potential problems?" Like what? Give an example. I thought of unintentionally passing an empty string to a method when it doesn't make sense for the method, for example. Many methods in the .NET Framework throw 'NullReferenceExceptions' if 'Nothing' is passed to them in a 'String' parameter because 'Nothing' doesn't make sense to this method. The same applies to zero-length strings which do not contain data which is meaningful to the method. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> > I thought of unintentionally passing an empty string to a method when it Does this method throw an exception on empty strings as well? If not, you've > doesn't make sense for the method, for example. Many methods in the .NET > Framework throw 'NullReferenceExceptions' if 'Nothing' is passed to them > in a 'String' parameter because 'Nothing' doesn't make sense to this > method. The same applies to zero-length strings which do not contain data > which is meaningful to the method. proved my point, not yours. You can't give describe a concrete example why unitialized strings should be the *norm* rather than the exception (pun intended)???? Here I'll give you one (that seemingly supports your case, but ultimately proves mine (in the end)): Setting an element in an XML document (or field in a dataset) to Nothing causes it to not be rendered when the XML stream is rendered (either as a file or otherwise). That's great- it's efficient for bandwidth reasons- and it totally supports your case. The file might look like this <persons> <person> <firstname>Joe</firstname> <address>Some address</address> <city>Some city</city> <state>Some state</state> </person> <person> <firstname>Tom</firstname> <lastname>Jefferson</lastname> <address>Some address</address> <city>Some city</city> <state>Some state</state> </person> </persons> Notice the missing lastname in the first person element. That's great! What could be wrong with that? Nothing if that was indeed your INTENTION. But if your intention was to have a user load that sheet into Excel, you'd be in for a surprise.... Excel renders the file as firstname | address | city | state | lastname Doh! That's not I wanted! Again, Nothing is an "exceptional" thing that you should use when you NEED it for a particular purpose. Don't use it just because the VB runtime allows you to do all sorts of things on a Nothing-String. "CMM" <cmm@nospam.com> schrieb: This depends on the particular case. If the method can cope with "", then >> I thought of unintentionally passing an empty string to a method when it >> doesn't make sense for the method, for example. Many methods in the .NET >> Framework throw 'NullReferenceExceptions' if 'Nothing' is passed to them >> in a 'String' parameter because 'Nothing' doesn't make sense to this >> method. The same applies to zero-length strings which do not contain data >> which is meaningful to the method. > > Does this method throw an exception on empty strings as well? If not, > you've proved my point, not yours. it will work, otherwise an appropriate exception ('ArgumentException') is thrown. 'NullReferenceException' is thrown if 'Nothing' is passed to the method. > You can't give describe a concrete example why unitialized strings should If they were the exception 'String' would have made a value type or a type > be the *norm* rather than the exception (pun intended)???? with value type semantics. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> >>so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) Well ,,,,, i learned a lot from Francesco and his assistents , to me he is > > Then I guess I'll have to disagree with them, it wouldn't be the first > time. the ultimate Guru also for the fact that when he recomends something he has a good explanation why or why not to do it however as i said before this book is about "practical guidelines and best practices" if you feel you do not need them don`t use them By the way the book is also stating that it addopted the internal guidelines of MS > Do they also recommend catch-all exception handling (or On Error No they recomend the opposite ,,,, use it as few as possible ( it is better > Resume Next style programming)? > to check for yourself if possible as relying on the exception object , and they tell to stay away from on error syntax ) In this thread i am fully with Carlos , he reflects my opinion maybe it is a mind twist that we share the same as i also started on the C64 :-) regards Michel Posseth [MCP] Show quoteHide quote "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> schreef in bericht news:e$nVucOMGHA.2992@tk2msftngp13.phx.gbl... > >According to "practical guidelines and best practices for Microsoft > >Visual >>Basic and Visual C# Developers" >> >>so by Francesco Balena and Giusseppe Dimauro and MS Press it is :-) > > Then I guess I'll have to disagree with them, it wouldn't be the first > time. > > >>Explicit assignment avoids NullReferenceException errors when referencing >>the string and simplifies code ( because the string doesn`t have to be >>tested against null ) > > I won't trade correctness for simplicity. Assigning "" to strings by > default, just to avoid NullReferenceExceptions, feels like a hack that > will just hide the actual problem. Exceptions can be good things if > they help you find errors during development, suppressing them is > taking the easy way out. > > Do they also recommend catch-all exception handling (or On Error > Resume Next style programming)? > > > Mattias > > -- > Mattias Sjögren [C# MVP] mattias @ mvps.org > http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com > Please reply only to the newsgroup. "m.posseth" <poss***@planet.nl> wrote in message Are these equivalentnews:uIV$vt$LGHA.2416@TK2MSFTNGP15.phx.gbl... > it is considered good coding practice to initialize string values with a > empty string value > > dim x as string ="" > or > dim x as string=string.empty > > I mean, does x end up the same? Thanks " academic" <acade***@a-znet.com> schrieb: Yes, it ends up in an empty string (string of length zero) too.>> it is considered good coding practice to initialize string values with a >> empty string value >> >> dim x as string ="" >> or >> dim x as string=string.empty > > Are these equivalent > > I mean, does x end up the same? -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> Thanks
Show quoteHide quote "Herfried K. Wagner [MVP]" <hirf-spam-me-here@gmx.at> wrote in message news:eml97ZAMGHA.3984@TK2MSFTNGP14.phx.gbl... >" academic" <acade***@a-znet.com> schrieb: >>> it is considered good coding practice to initialize string values with a >>> empty string value >>> >>> dim x as string ="" >>> or >>> dim x as string=string.empty >> >> Are these equivalent >> >> I mean, does x end up the same? > > Yes, it ends up in an empty string (string of length zero) too. > > -- > M S Herfried K. Wagner > M V P <URL:http://dotnet.mvps.org/> > V B <URL:http://classicvb.org/petition/> "" and string.empty are perfectly equivalant
prove ?? dim x as string ="" dim y as string = string.empty string.ReferenceEquals(x,y) this will display true regards Michel Posseth [MCP] Show quoteHide quote " academic" <acade***@a-znet.com> schreef in bericht news:u7FGUTAMGHA.676@TK2MSFTNGP10.phx.gbl... > > "m.posseth" <poss***@planet.nl> wrote in message > news:uIV$vt$LGHA.2416@TK2MSFTNGP15.phx.gbl... >> it is considered good coding practice to initialize string values with a >> empty string value >> >> dim x as string ="" >> or >> dim x as string=string.empty >> >> > Are these equivalent > > I mean, does x end up the same? > > Thanks > great thanks
Show quoteHide quote "m.posseth" <poss***@planet.nl> wrote in message news:%23JL0VaAMGHA.3432@tk2msftngp13.phx.gbl... > "" and string.empty are perfectly equivalent > > prove ?? > > > dim x as string ="" > dim y as string = string.empty > > string.ReferenceEquals(x,y) > > this will display true > > > regards > > Michel Posseth [MCP] > > > " academic" <acade***@a-znet.com> schreef in bericht > news:u7FGUTAMGHA.676@TK2MSFTNGP10.phx.gbl... >> >> "m.posseth" <poss***@planet.nl> wrote in message >> news:uIV$vt$LGHA.2416@TK2MSFTNGP15.phx.gbl... >>> it is considered good coding practice to initialize string values with a >>> empty string value >>> >>> dim x as string ="" >>> or >>> dim x as string=string.empty >>> >>> >> Are these equivalent >> >> I mean, does x end up the same? >> >> Thanks >> > > The performance differences aren't really noticeable but there IS a
difference! In the IL: ("") compiles to ldstr "" --- Which means, LoadString, Look it up ("it" being the char array) in the string table, create a new reference to the existing string. (String.Empty) compiles to ldsfld String::Empty --- Which means, LoadField, push an already existing reference. Look at it this way: At its core, S = "" is the same thing as S = New String(New Char() {}) While S = String.Empty is just quite literally S = String.Empty. If you have "" executed 50 times in your running code, you have created (and instantly discarded) 50 object references. Sure, all the objects point to the same string in the string table but still! 2) Lastly, "" forces a scan of the string table (obviously) while String.Empty does not. Sounds like the last word to me
Thanks Show quoteHide quote "CMM" <cmm@nospam.com> wrote in message news:uC1rLjCMGHA.3264@TK2MSFTNGP11.phx.gbl... > The performance differences aren't really noticeable but there IS a > difference! > > In the IL: > ("") compiles to ldstr "" --- Which means, LoadString, Look it up ("it" > being the char array) in the string table, create a new reference to the > existing string. > (String.Empty) compiles to ldsfld String::Empty --- Which means, > LoadField, push an already existing reference. > > Look at it this way: > At its core, S = "" is the same thing as S = New String(New Char() {}) > While S = String.Empty is just quite literally S = String.Empty. > > If you have "" executed 50 times in your running code, you have created > (and instantly discarded) 50 object references. Sure, all the objects > point to the same string in the string table but still! > > 2) Lastly, "" forces a scan of the string table (obviously) while > String.Empty does not. > > > -- > -C. Moya > www.cmoya.com > " academic" <acade***@a-znet.com> wrote in message ... To clarify... because your original post brought up slightly different > Sounds like the last word to me questions: 1) Nothing = Nothing. You're right in assuming that nothing is allocated. A string initializes to Nothing by default. This leads to bugs... if not for you then for someone down the road who might have to maintain your code! While VB's type coercion often hides this from you... for instance trying s.Length() on a Nothing string will result in an exception. VB won't help you there. 2) "" = New String(New Char() {}) 3) String.Empty = .... um, well, it equals exactly "" ;-) Obviously, Dim s As String = String.Empty is by far the most efficient and safest coding practice. I recommend it. Show quoteHide quote " academic" <acade***@a-znet.com> wrote in message news:ufSKEqCMGHA.2276@TK2MSFTNGP15.phx.gbl... > Sounds like the last word to me > > > Thanks > > "CMM" <cmm@nospam.com> wrote in message > news:uC1rLjCMGHA.3264@TK2MSFTNGP11.phx.gbl... >> The performance differences aren't really noticeable but there IS a >> difference! >> >> In the IL: >> ("") compiles to ldstr "" --- Which means, LoadString, Look it up ("it" >> being the char array) in the string table, create a new reference to the >> existing string. >> (String.Empty) compiles to ldsfld String::Empty --- Which means, >> LoadField, push an already existing reference. >> >> Look at it this way: >> At its core, S = "" is the same thing as S = New String(New Char() {}) >> While S = String.Empty is just quite literally S = String.Empty. >> >> If you have "" executed 50 times in your running code, you have created >> (and instantly discarded) 50 object references. Sure, all the objects >> point to the same string in the string table but still! >> >> 2) Lastly, "" forces a scan of the string table (obviously) while >> String.Empty does not. >> >> >> -- >> -C. Moya >> www.cmoya.com >> > > Carlos
> A bug is not a hang from the program, a bug is that the result is something > 1) Nothing = Nothing. You're right in assuming that nothing is allocated. > A string initializes to Nothing by default. This leads to bugs... else than there should be. Initializing to zero can be in some situations be forgiving full. However I assume that they would be happier on wallstreet with your program if it would hang, than that on all the invoices would come spaces as price. Which is as well not prevented with setting it to Nothing, however has still more a change that the program will hang than that you intialize it. Just my thought Cor "CMM" <cmm@nospam.com> wrote in message What does "Look it up" mean.news:uC1rLjCMGHA.3264@TK2MSFTNGP11.phx.gbl... > The performance differences aren't really noticeable but there IS a > difference! > > In the IL: > ("") compiles to ldstr "" --- Which means, LoadString, Look it up ("it" > being the char array) in the string table, create a new reference to the > existing string. Does it look up every time I assign a value to a string variable to see if that value is already in a table? >The performance differences aren't really noticeable but there IS a Can you post some numbers?>difference! >If you have "" executed 50 times in your running code, you have created (and You make it sound like an object reference is an object in itself that>instantly discarded) 50 object references. Sure, all the objects point to >the same string in the string table but still! requires dynamic memory allocation. But they are just "pointers" stored in preallocated space in registers, on the stack or in a field. No dynamic allocation needed, so I don't see your point. Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "m.posseth" <poss***@planet.nl> schrieb I've never done it.> it is considered good coding practice to initialize string values > with a empty string value > > dim x as string ="" > or > dim x as string=string.empty Armin >But with "" it is - correct? Yes. But that shouldn't stop you from using it if appropriate.>The system seems to handle a null the same as "". Depends on what you mean by "the system". The VB language andlibraries often tries to hide the difference but in the the .NET framework there's usually a significant difference. >What about passing to a Windows API? Yes.> >Is there a difference between passing "" and passing Nothing? Mattias -- Mattias Sjögren [C# MVP] mattias @ mvps.org http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com Please reply only to the newsgroup. "Mattias Sjögren" <mattias.dont.want.spam@mvps.org> wrote in message I can't think of a situation where it is appropriate ( which is not to imply news:eRfGGMAMGHA.3432@tk2msftngp13.phx.gbl... > >But with "" it is - correct? > > Yes. But that shouldn't stop you from using it if appropriate. that I think there isn't any) > That's explains a lot> >>The system seems to handle a null the same as "". > > Depends on what you mean by "the system". The VB language and > libraries often tries to hide the difference but in the the .NET > framework there's usually a significant difference. > I believe passing Nothing would cause a zero to be put on the stack.> >>What about passing to a Windows API? >> >>Is there a difference between passing "" and passing Nothing? > > Yes. > What does pass "" do? Thanks Academic,
A "" pases a string with one charachter "" A Nothing passes an object with no reference. You cam try this \\\ Dim myfirstobject As Object = Nothing Dim mysecondobject As String If myfirstobject Is mysecondobject Then MessageBox.Show("we both are Nothing") End If If myfirstobject IsNot "" Then MessageBox.Show("we are different") End If If myfirstobject IsNot String.Empty Then MessageBox.Show("we are different") End If /// I hope this gives some idea's Cor "Cor Ligthert [MVP]" <notmyfirstn***@planet.nl> schrieb: I think you wanted to type "with zero characters" as strings in VB are not > A "" pases a string with one charachter "" null-terminated. -- M S Herfried K. Wagner M V P <URL:http://dotnet.mvps.org/> V B <URL:http://classicvb.org/petition/> Herfried,
> A "" pases a string with one charachter "" Exact I typed it, saw what bs I wrote, wanted to correct it, could not > > I think you wanted to type "with zero characters" as strings in VB are not > null-terminated. > direct get the right term and forgot it Thanks, Cor |
|||||||||||||||||||||||