Jump to content
Xtreme .Net Talk

Recommended Posts

  • Leaders
Posted

While translating some of my old VB to C#, I found this amusing line of code in a class I wrote a while ago.

If [u][b][i]Not Me Is Nothing[/i][/b][/u] Then
   Save(Medium.GetKey)
End If

I couldn't help but share this stunningly witty piece of code. It brings Descartes' famous quote to mind, "I think, therefore I am." Perhaps this is why I don't program for a living.

 

Anyone else?

[sIGPIC]e[/sIGPIC]
  • *Experts*
Posted

I like it :)

 

I wonder if anyone has some code like:

If Me.Exists() Then

' Do Something

Else

' Who cares - I don't exist!

End If

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
  • Leaders
Posted (edited)
I like it :)

 

I wonder if anyone has some code like:

 

If Me.Exists() Then

' Do Something

Else

' Who cares - I don't exist!

End If

 

-ner

Actually, I have something similar, but this code actually does something more than confirm it's existence.

if(this.Exists()) {
// Load settings if they exist.
Load();
} else {
// Default values
_ProfRender = false;
_DBPath = System.IO.Path.Combine(
	Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
	DataFolder);
}

This is the code used to initialize a settings manager class I wrote. The exists method returns whether or not the serialized settings exist.

Edited by snarfblam
[sIGPIC]e[/sIGPIC]
  • 2 weeks later...
Posted
LoL WTFuk

I can't stand VB or VB.NET It allows to much non OO style programming!!!!!!!!!!!!!!!!!

And the fact that the Object Class is at the root of the inheritence hierarchy is basically the epitome of Object Oriented... I've found that you have to go out of your way pretty hard to NOT be OO.

Posted

Yeh, even though now in .NET 2.0 they have the IsNot keyword, I still use the old If Not Blah Is Nothing syntax because it has grown on me :-)

 

kurf, you need to go back to school or something if you honestly believe that. Show me how to NOT program OO in VB.NET!!!!

  • Leaders
Posted

I never really appreciated the Is operator in the first place. I understand that it is there to avoid confusion between equal references and equal values, but people seem to get the right idea when using C#.

 

I actually started writing code like this when I switched over to C#:

// Before it occured to me to use the != operator for reference types
if(!(MyObject == e.Sender)) {
   // Do things and junk
}

[sIGPIC]e[/sIGPIC]
Posted
I never really appreciated the Is operator in the first place. I understand that it is there to avoid confusion between equal references and equal values' date=' but people seem to get the right idea when using C#.[/quote']

 

You do have to be careful, though. If you've overloaded the equals operator and you want to check for null references you have to cast the class object to type Object in order to make sure that you actually check the reference and not call the equals operator you wrote for the class object, which will fail for a null reference without the reference check. The is operator makes that casting unnecesary:

 

if ((object)mySuperObject == null)
{ 
  /* Do Something, probably return */
}

If mySuperObject is nothing Then
''Do Something, probably return
End If

 

And of course, the IsNot operator is pantented technology. Go figure how that happened (not trying to change subject).

Posted
I'm just as intruiged as to how you knew it was patented as to how it became patented. I must admit that as I'm used to c# I sometimes get caught out by the use of the 'Is' operator. I'm normally alright if I think through a statement carefully but if I just give it a cursory glance I often get the wrong idea. Especially when I was making a TypeConverter and using GetType and TypeOf.
Anybody looking for a graduate programmer (Midlands, England)?
  • Leaders
Posted
You do have to be careful' date=' though. If you've overloaded the equals operator and you want to check for null references you have to cast the class object to type Object in order to make sure that you actually check the reference and not call the equals operator you wrote for the class object, which will fail for a null reference without the reference check. The is operator makes that casting unnecesary:[/quote']

Good point. I was kind of wondering about that. It brings up a question, though: How does inheritance play into operator overloading. Does operator overloading behave more like shadowing (hence it would be carried up the inheritance chain into derived classes, but not the other way)? Or is it more like overriding (down-casting won't prevent invocation of overriding method)?

[sIGPIC]e[/sIGPIC]
Posted
I don't think I quite understand...it's more like overloading. You can still cast an object to its base and use the overloaded operator you intend to use. If you don't overload the operators (all are required if you create one) then I think you will use the base class's operators. That's why you can still use == on an object you declare even though you never wrote the == operator - your using the Object Class's Equals operator.
  • Leaders
Posted

Oh.. my confusion stems from the fact that I didn't realize that operator overloads were static (can you tell that I've never overloaded an operator before?). I suppose overloading would be the appropriate term.

 

I'm kind of weary of the fact that operator overloading can change the behavior of the == operator. In C++ to compare for equal reference, you can compare pointers or addresses, but you must dereference a pointer to use the overloaded operator. In other words, the reference itself is a different type than the class and the operators function differently on these different types, hence you are adding functionality, but not modifying it, where in C# you can introduce ambiguity since you can overload the operator that previously compared the references.

[sIGPIC]e[/sIGPIC]
Posted
In other words' date=' the reference itself is a different type than the class and the operators function differently on these different types, hence you are adding functionality, but not modifying it, where in C# you can introduce ambiguity since you can overload the operator that previously compared the references.[/quote']

You raise a very valid point. That has always been on of the things that has bothered my about both VB.Net and C#, the whole value vs reference types (hidden pointers). When overloading the operator you have to be sure to call the Object Class's equals operator so that you build the reference check into your equals operator. That way you get both checks for equality in your operator. But that shouldn't be too different from other times you would overload a base class implementation -- the base class will almost always be called at some point (base.Something()).

 

Operator overloading is quite powerful. I wonder if they put it in the new VB.Net?

Posted (edited)

To get this back on subject of CrAzY code, here's a snippet from my personal collection. Actually, a coworker wrote this on a project he and I were working on together about 2.5 years ago, back when we were still quite new to VB and very new to .Net:

If Not DataFileNodeList Is Nothing Then
  Dim FileList As New ArrayList
  For Each child As XmlNode In DataFileNodeList
     Dim Path As String = child.Item("Full-Path").FirstChild.Value
     FileList.Add(Path)
  Next

  Dim MichaelsFaultList(FileList.Count - 1) As String
  Dim Counter As Integer
  For Each Item As String In FileList
     MichaelsFaultList(Counter) = Item
     Counter = Counter + 1
  Next
  openAndInsertFiles(MichaelsFaultList)
End If

So, openAndInsertFiles required a string array, the XML was unpacked into an arrayList for convenience, and then becuase I required a string array in openAndInsertFiles, my friend created the "MichaelsFaultList" string array and send that to me becuase he felt it was an unecesary step. sheesh.

Edited by mskeel
  • *Experts*
Posted

Since it's off-top, I'll keep it short:

I'm kind of weary of the fact that operator overloading can change the behavior of the == operator

 

There's an excellent reference on the difference between ReferenceEquals(), static Equals(), instance Equals() and operator== in C# in the book Effective C# - 50 specific ways to improve your C#.

 

For operator== you normally only override for value types - and you should ALWAYS override it for value types, if you're going to compare your value types. You override it for performance only. For a reference type you would almost never override operator==.

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
  • Leaders
Posted

I personally wouldn't overload the == operator. Operator overloading isn't my style anyways, since it doesn't do anything but assign function calls to operators, it is really just syntactical sugar. (What is it at the IL level? Are the functions marked by flags? Or do they have special names like contructors?) But I can think of a dozen cases where you might want to overload the == operator on a class. For instance, if a class is instantiated with data loaded from a file, and you want to compare different instances for duplicate data, or if you have a class related to something like a domain name, registry key, or file, and want to check if objects refer to the same domain/key/file/etc.

 

I can see people doing it left and right, and then shooting themselves in the foot when they unwittingly call the == overload because they are trying to check for equal references.

[sIGPIC]e[/sIGPIC]
  • 3 weeks later...
Posted (edited)

Operator overloading is the king of cool, man. I've never had any troubles with, only troubles without it. And it's soooo easy in the new VB. It just feels great to be able to do that in VB.

        Public Shared Operator =(ByVal super1 As SuperObj, ByVal super2 As SuperObj) As Boolean
           If super1 Is Nothing AndAlso super2 Is Nothing Then
               Return True
           End If

           if super1 is nothing orelse pair2 is nothing then
               Return False
           End If
          
         If super1._string1 = super2._string1 AndAlso _
              super1._string2 = super2._string2 Then
               Return True
           End If

           Return False
       End Operator
       '
       ' and now, the required not equals..
       Public Shared Operator <>(ByVal super1 As SuperObj, ByVal super2 As SuperObj) As Boolean
           Return Not (super1 = super2)
       End Operator

Looks like the message board needs to be updated for .Net 2.0 key words.

Edited by mskeel
  • Leaders
Posted
I've never had any troubles with, only troubles without it.[/Quote]

I don't understand how you have trouble without operator overloads. Like I said, it is syntactical sugar. You just use operators instead of function names and the substitution is done for you at compile.

 

Public Shared Function Equals(ByVal Super1 As SuperObj, ByVal Super2 As SuperObj) As Boolean
   If Object.ReferenceEquals(Super1, Super2) Then Return True

   If Super1 Is Nothing OrElse super2 Is Nothing Then
       Return False
   End If
          
   If Super1._String1 = Super2._String1 AndAlso _
      Super1._String2 = Super2._String2 Then
       Return True
   End If

   Return False
End Function
'
' and now, the not equals is not required... We can always use Not Equals()

 

One thing that surprises me a little is that the << and >> operators aren't overloaded for streams.

[sIGPIC]e[/sIGPIC]
Posted
Like I said' date=' it is syntactical sugar.[/quote']Have you ever had sugar-free cookies? Maybe a friend with diabetes gave them to you. They taste terrible. I think sugar is absolutely necesary. You are more than welcome to code however you want (wordy), but with it being so convenient and easy, I see no reason not to overload the equals operator for most objects. Allright, so maybe overloading == doesn't get you going, but overlading + surely must. That's pretty hard core, being able to simply add a custom class. Operator overloading is more than just sugar at that point.

 

 

One thing that surprises me a little is that the << and >> operators aren't overloaded for streams.
Are these used for streams at all in VB.Net? I know they are in C++ and you can overload them in that context in that language. But they are also used for bitwise operations, so depending on the context they can mean different things.
  • Leaders
Posted

Sugar free food still nourishes, and all that sugar isn't good for you. You need to get your energy from complex carbs. Maybe if your parents fed you better growing up, you would be able to appreciate sugar free cookies. Have some carrot sticks. But, yes, I have eaten sugar free everything because I know plenty of people who think that diet/fat-free/sugar-free food is the solution to a weight problem.

 

In all seriousness, syntactical sugar is ultimately just that. I make a distinction between something like anonymous methods, which, from an extreme point of view, could be considered syntactical sugar for extra classes with methods to pass as delegates, and something like operator overloading which makes a simple substitution of "opAddition" for a "+". Operator overloading does not really add or modify functionality. You can argue that it modifies the behavior of operators, but in reality it replaces operators with functions at compile time and doesn't really behave like an operator at all. It makes your code prettier with a simple modification of syntax but without a modification of the analogy between what your code says and what it actually does, hence the name syntactical sugar. It is nice, and I can appreciate it, but I would never ever call it necessary. I will never mind using a function named Add().

 

<< and >> are bitwise operators in C++, but they are overloaded and generally used for streams. Obviosly you can't perform a bitshift on a stream so there isn't any ambiguity. There is no conflict in C++ and I can't imagine that there would be in VB. To be perfectly honest, when streams were introduced in VB I didn't know what to do with them because they didn't overload the << and >> operators.

 

Dim MySteam As New FileStream("C:\\Textfile.txt", FileMode.Open, FileAccess.Write)
MyStream << "There is no reason why we can't use << or >> on a stream."
MyStream << Environment.NewLine << "This is on the next line." << Environment.NewLine
MyStream << "Bitshift: 5 << 2" << (5 << 2)
'That last one might hurt your head, but that is messy coding, not ambiguous operators

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...