Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
POKEMAN SAM
Jul 8, 2004
We have concrete classes, like MyObject as well as an interface for each, like IMyObject. We construct these objects on demand, so we have potentially many objects that are semantically identical, but are different CLR objects. This means that we can't do myObjectA == myObjectB, because that does a reference comparison and we can't overload the == operator for an interface. This StackOverflow question sums it up: http://stackoverflow.com/questions/728434/operator-overloading-with-interface-based-programming-in-c.

It's loving annoying.

Adbot
ADBOT LOVES YOU

Sedro
Dec 31, 2008
Like they say in your link, you should use Equals() to compare for semantic equality and leave operator== alone (except for immutable objects, where you can get away with it). It sucks that Equals() has to be called from one side, but the only other solution would be a utility class. To make things clearer, you could put IEquatable<IMySemanticallyIdenticalObject> onto IMyObject and vice versa.

POKEMAN SAM
Jul 8, 2004

Sedro posted:

Like they say in your link, you should use Equals() to compare for semantic equality and leave operator== alone (except for immutable objects, where you can get away with it). It sucks that Equals() has to be called from one side, but the only other solution would be a utility class. To make things clearer, you could put IEquatable<IMySemanticallyIdenticalObject> onto IMyObject and vice versa.

To make sure I'm clear, the two objects that are semantically equal are both IMyObjects that are even both the same concrete class under the hood. This is guaranteed, which is why it's kind of annoying that by adding this interface as a level of indirection to keep the API clean (separating implementation from the interface) means that we can no longer use ==

epswing
Nov 4, 2003

Soiled Meat
What's so bad about Equals?

Sedro
Dec 31, 2008
It's weird to compare two objects using A.Equals(B) because now A is in charge of the comparison, and comparing two objects should be neutral. And of course you have to check if A is null. You can get into cases where A.Equals(B) != B.Equals(A). It makes more sense to do ComparisonUtil.Equals(A, B). Operator== is exactly this plus nicer syntax.

It's too bad that Object.operator== uses ReferenceEquals instead of Equals.

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:

Sedro posted:

It's weird to compare two objects using A.Equals(B) because now A is in charge of the comparison, and comparing two objects should be neutral. And of course you have to check if A is null. You can get into cases where A.Equals(B) != B.Equals(A). It makes more sense to do ComparisonUtil.Equals(A, B). Operator== is exactly this plus nicer syntax.

It's too bad that Object.operator== uses ReferenceEquals instead of Equals.

If "A.Equals(B) != B.Equals(A)", then your Equals implementation isn't correct.

And you can simply call the static method object.Equals(object, object), which will first check reference equality and nulls, and then call the overridable obbject.Equals method.

So just override Equals and call "object.Equals(a, b)" instead of "a == b", and you're set.

epswing
Nov 4, 2003

Soiled Meat

dwazegek posted:

If "A.Equals(B) != B.Equals(A)", then your Equals implementation isn't correct.

Right.

Maybe "just use .Equals and move on with your life" has already sunk in because I learned Java in school, and string comparison required the use of .equals.

POKEMAN SAM
Jul 8, 2004

epswing posted:

Right.

Maybe "just use .Equals and move on with your life" has already sunk in because I learned Java in school, and string comparison required the use of .equals.

Exactly. I've always felt that the whole Equals thing for strings is one of the weak points in Java, and it's annoying that I have to deal with the same problem in C# as a result of choosing to follow what I believe is a better design pattern (like having an assembly with the interfaces and having the application deal with the interfaces and then having a separate assembly that implements the interface so that we can swap out implementations easier, which is a design requirement.) If we were just dealing with the concrete class all over, then we could use the regular == because it's overloaded, but because operator overloading isn't available for interfaces (I assume because operators need non-virtual bindings maybe?) we can't specify our own == for the interface.

Edit: I also worry about it being unobvious; since the team is obviously used to working with == doing what they want in all other cases that they might use it here and subtle bugs will creep in. This wouldn't be as big of a deal if we could test for that, but I'm not sure how I'd do that other than writing something that looks at the IL output for instances comparing two IMyObjects by their references (I'm not even sure if that's plausible.)

POKEMAN SAM fucked around with this message at 17:26 on Dec 2, 2010

wwb
Aug 17, 2004

While we are on operator overloading, lets remember to cover the null cases for ==/!= overloading.

This just broke a pretty big system here. Yes, the tests should have covered this.

Dr Monkeysee
Oct 11, 2002

just a fox like a hundred thousand others
Nap Ghost
I've found the problem with == in C# is it's ambiguous when it's a reference comparison and when it's a value comparison. The framework types often don't make it very obvious, whereas Equals is usually pretty clear. You can probably do fine just assuming "reference types do a reference comparison and value types do a value comparison" but I've run into enough exceptions that I'm gun-shy at this point.

In practice I find that using Equals on strings is almost always required though because I nearly always have to specify a StringComparison value different from the default, which the == operator doesn't allow you to do.

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!
Not that it's any better, but if you really prefer to use == for strings you can always do x.ToLowerInvariant() == y.ToLowerInvariant()

POKEMAN SAM
Jul 8, 2004

Orzo posted:

Not that it's any better, but if you really prefer to use == for strings you can always do x.ToLowerInvariant() == y.ToLowerInvariant()

Is this what the Equals function actually does though? This seems to me like it would be two more string allocations/copies/conversions than the comparison would do.

epswing
Nov 4, 2003

Soiled Meat
nm

epswing fucked around with this message at 04:36 on Dec 3, 2010

bobua
Mar 23, 2003
I'd trade it all for just a little more.

code:
foreach (KeyValuePair<string, DBmember> kvp in Program.memberlist.ToList())
            {
                ListViewItem item1 = new ListViewItem(kvp.Key);
                item1.UseItemStyleForSubItems = false;
                foreach (string s in kvp.Value.ToArray())
                {
                    item1.SubItems.Add(s);
                }
                foreach (ListViewItem.ListViewSubItem item in item1.SubItems) //find a cell with the number one, color it green.
                {
                    if (item.Text == "1")
                        item.BackColor = Color.Green;
                }
                this.listView1.Items.Add(item1);
            }
this(working) code fills a listview box with the items in a dictionary. If the number 1 is found in one of the subitems, it colors that 'cell' green. I can't help but think there is a better way to do this.

Orzo
Sep 3, 2004

IT! IT is confusing! Say your goddamn pronouns!

Ugg boots posted:

Is this what the Equals function actually does though? This seems to me like it would be two more string allocations/copies/conversions than the comparison would do.
Possibly, I didn't really mean in a high performance situation, in which case I'd probably make one StringComparer and use that over and over.

Sedro
Dec 31, 2008

bobua posted:

this(working) code fills a listview box with the items in a dictionary. If the number 1 is found in one of the subitems, it colors that 'cell' green. I can't help but think there is a better way to do this.

You can do this very concisely in xaml. There's no reason for you to use code-behind.

code:
<ListView ItemsSource="{Binding memberList}" DisplayMemberPath="Value">
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Value}" Value="1">
                    <DataTrigger.Setters>
                        <Setter Property="Background" Value="Green"/>
                    </DataTrigger.Setters>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>
Edit: Actually, is that a WinForms ListView? If so, good luck with that :unsmith:

Sedro fucked around with this message at 08:50 on Dec 3, 2010

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:

Ugg boots posted:

Is this what the Equals function actually does though? This seems to me like it would be two more string allocations/copies/conversions than the comparison would do.

No, it doesn't. Using one of the StringComparers (or using the Equals overload that takes an StringComparison) is basically always faster than converting the string to upper/lower and then comparing it. And it's less code to, because you don't have to check for nulls first.

Smugdog Millionaire
Sep 14, 2002

8) Blame Icefrog

dwazegek posted:

No, it doesn't. Using one of the StringComparers (or using the Equals overload that takes an StringComparison) is basically always faster than converting the string to upper/lower and then comparing it. And it's less code to, because you don't have to check for nulls first.

Who said I ever check for nulls?

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Sedro posted:

You can do this very concisely in xaml. There's no reason for you to use code-behind.

Edit: Actually, is that a WinForms ListView? If so, good luck with that :unsmith:

Yes, it's winforms. Why do you say that? :(

I started with listbox instead of listview, but it seemed listview was closer to how I wanted to represent the data. It still isn't how I'd like it to look in the end, but I'm afraid I'm going to have to build a custom control or learn wpf to get what I want, which is daunting for someone still trying to get the basics of programming and c#.

Sprawl
Nov 21, 2005


I'm a huge retarded sperglord who can't spell, but Starfleet Dental would still take me and I love them for it!

bobua posted:

code:
foreach (KeyValuePair<string, DBmember> kvp in Program.memberlist.ToList())
            {
                ListViewItem item1 = new ListViewItem(kvp.Key);
                item1.UseItemStyleForSubItems = false;
                foreach (string s in kvp.Value.ToArray())
                {
                    item1.SubItems.Add(s);
                }
                foreach (ListViewItem.ListViewSubItem item in item1.SubItems) //find a cell with the number one, color it green.
                {
                    if (item.Text == "1")
                        item.BackColor = Color.Green;
                }
                this.listView1.Items.Add(item1);
            }
this(working) code fills a listview box with the items in a dictionary. If the number 1 is found in one of the subitems, it colors that 'cell' green. I can't help but think there is a better way to do this.


Well that is kinda silly.

You can easily just go and find the item your looking for using
code:
item1.ListView.Items.Find()

PhonyMcRingRing
Jun 6, 2002

bobua posted:

code:
foreach (KeyValuePair<string, DBmember> kvp in Program.memberlist.ToList())
            {
                ListViewItem item1 = new ListViewItem(kvp.Key);
                item1.UseItemStyleForSubItems = false;
                foreach (string s in kvp.Value.ToArray())
                {
                    item1.SubItems.Add(s);
                }
                foreach (ListViewItem.ListViewSubItem item in item1.SubItems) //find a cell with the number one, color it green.
                {
                    if (item.Text == "1")
                        item.BackColor = Color.Green;
                }
                this.listView1.Items.Add(item1);
            }
this(working) code fills a listview box with the items in a dictionary. If the number 1 is found in one of the subitems, it colors that 'cell' green. I can't help but think there is a better way to do this.

According to MSDN, ListViewSubItemCollection's Add method returns the SubItem object it creates. So you could do something like this:

code:
foreach (KeyValuePair<string, DBmember> kvp in Program.memberlist.ToList())
            {
                ListViewItem item1 = new ListViewItem(kvp.Key);
                item1.UseItemStyleForSubItems = false;
                foreach (string s in kvp.Value.ToArray())
                {
                  var newSubItem = item1.SubItems.Add(s);
                  if (s == "1") {
                      newSubItem.BackColor = Color.Green 
                  }
                }
                this.listView1.Items.Add(item1);
            }

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Sprawl posted:

Well that is kinda silly.

You can easily just go and find the item your looking for using
code:
item1.ListView.Items.Find()

Wouldn't this return the item, even if I told it to search the sub items?

Phony, that seemed to work great, thanks.

PhonyMcRingRing
Jun 6, 2002

bobua posted:

Wouldn't this return the item, even if I told it to search the sub items?

Phony, that seemed to work great, thanks.

One other thing you might want to consider as well. Hold off on adding all the ListItems to the ListView until you've created all of them. Then add them with a call to ListView.Items.AddRange. It'll speed up the rendering of it dramatically.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

PhonyMcRingRing posted:

One other thing you might want to consider as well. Hold off on adding all the ListItems to the ListView until you've created all of them. Then add them with a call to ListView.Items.AddRange. It'll speed up the rendering of it dramatically.

code:
foreach (KeyValuePair<string, DBmember> kvp in Program.memberlist.ToList())
            {
                ListViewItem listviewitem = new ListViewItem(kvp.Key);
                listviewitem.UseItemStyleForSubItems = false;
                foreach (string s in kvp.Value.ToArray())
                {
                    var newSubItem = listviewitem.SubItems.Add(s);
                    if (s == "1")
                    { newSubItem.BackColor = Color.Green; }
                    else if (s == "0")
                    { newSubItem.BackColor = Color.Yellow; }
                    else if (s == "-1")
                    { newSubItem.BackColor = Color.Red; }
                }
                l.Add(listviewitem);
            }
i created a listview item collection with my listview as the owner, but I don't think that's the same thing you were talking about... I assume you mean to add them all to an array or something, then add them at the end all at once?

Zhentar
Sep 28, 2003

Brilliant Master Genius
That is what he meant. Or, more simply and about as effective, you can just call l.BeginUpdate before the loop, and l.EndUpdate afterwards. If you add items one at a time without doing that, the listview will do some redrawing automatically after every single one, adding a substantial amount of overhead.

go play outside Skyler
Nov 7, 2005


Hello, quick question:
Is it possible in Visual Web Developper 2010 to make a deployment build where the code-behind files (.aspx.cs) are editable? I'm making an app for my client and they would like to:
1. Review the code
2. Maybe modify things in the future

Since I don't think giving them the entire .sln solution/project is the best idea, I thought it'd be good to have some way of having the code NOT compiled, just make it do on-the-fly compilation.

I tried setting, in the package/publish settings, to deploy all files, but editing the .cs files doesn't do anything. All the code is compiled in a .dll in the bin/ folder.

PS: In case you can't tell I'm new to Visual Web Developper and the whole ASP.NET shenanigans

Thanks

MGshotgun
Jan 8, 2008

Would this be the right place to ask a simple question about a WP7 app? I am a complete beginner to programming in general, but cannot understand this problem even after staring at the documentation from msdn.

For learning purposes, I'm trying to make a simple app that will convert a user imputed height in feet and inches format to display what the total inches would be. Here is what I have so far:

code:
            int feet, inches, totalInches;
            string feetString = "";
            string inchesString = ""; 

            feetTextBox.Text = feetString; // user imputed feet
            feet = int.Parse(feetString);  // convert feetString to an int

            inchesTextBox.Text = inchesString;
            inches = int.Parse(inchesString);

            totalInches = feet * 12 + inches;  

            answerTextBlock.Text = totalInches.ToString(); 
This code gives me a Format Exception when I try to convert the feetString to an integer even though I am typing a number into the feetTextbox. Any insight on why I am getting the error?

Zhentar
Sep 28, 2003

Brilliant Master Genius
Maybe it would work better if you did feetString = feetTextBox.Text;?

MGshotgun
Jan 8, 2008

Zhentar posted:

Maybe it would work better if you did feetString = feetTextBox.Text;?

Hah, that worked. I knew it was something simple.

wwb
Aug 17, 2004

Sir Davey posted:


PS: In case you can't tell I'm new to Visual Web Developper and the whole ASP.NET shenanigans

Thanks

Actually, giving them the entire solution/project is the best idea. This will let them fix it after you are out of the picture.

Kekekela
Oct 28, 2004

Sir Davey posted:

Hello, quick question:
Is it possible in Visual Web Developper 2010 to make a deployment build where the code-behind files (.aspx.cs) are editable? I'm making an app for my client and they would like to:
1. Review the code
2. Maybe modify things in the future

Since I don't think giving them the entire .sln solution/project is the best idea, I thought it'd be good to have some way of having the code NOT compiled, just make it do on-the-fly compilation.

I tried setting, in the package/publish settings, to deploy all files, but editing the .cs files doesn't do anything. All the code is compiled in a .dll in the bin/ folder.

PS: In case you can't tell I'm new to Visual Web Developper and the whole ASP.NET shenanigans

Thanks

Haven't used Visual Web Dev, but there should be a "Allow this precompiled site to be updatable" checkbox or something similar either in the website properties or the publish dialog that you'd want to have checked.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

Need a point in the right direction here. I want to display some information in a way that a normal control won't let me(I think). Just as an example I'd like a listbox that works more like this one http://www.telerik.com/products/aspnet-ajax/listbox.aspx

That's web\ajax so I don't think it really applies to what I'm doing(winforms\c#), but I guess that's what I need to do, build a custom control? Every tutorial I find either has nothing to do with the graphical side of building your own control, or has something like changing the color of a button, which is just not much help.

So the question is, do I actually need to build my own control? Do I need to buy a book specific to the subject, or am I going about this all wrong?

Sprawl
Nov 21, 2005


I'm a huge retarded sperglord who can't spell, but Starfleet Dental would still take me and I love them for it!
Have you tried the ajax tool kit controls?

http://www.asp.net/ajax/ajaxcontroltoolkit/samples/

POKEMAN SAM
Jul 8, 2004

Sprawl posted:

Have you tried the ajax tool kit controls?

bobua posted:

That's web\ajax so I don't think it really applies to what I'm doing(winforms\c#), but I guess that's what I need to do, build a custom control?

Begby
Apr 7, 2005

Light saber? Check. Black boots? Check. Codpiece? Check. He's more machine than kid now.

bobua posted:

Need a point in the right direction here. I want to display some information in a way that a normal control won't let me(I think). Just as an example I'd like a listbox that works more like this one http://www.telerik.com/products/aspnet-ajax/listbox.aspx

That's web\ajax so I don't think it really applies to what I'm doing(winforms\c#), but I guess that's what I need to do, build a custom control? Every tutorial I find either has nothing to do with the graphical side of building your own control, or has something like changing the color of a button, which is just not much help.

So the question is, do I actually need to build my own control? Do I need to buy a book specific to the subject, or am I going about this all wrong?

What features from that list box do you need specifically? If you just need to move items from one list box to another, its not too difficult.

However, if you want to make it so each item in the list box has an image and other fancy poo poo, you might have to roll your own custom control, and I have never done that since it has always looked like a real pain in the rear end. There are other companies though that sell winforms controls and might have something that does what you want.

If possible, you might want to look at WPF, it might be easier to go that route instead of doing your own custom C# control.

bobua
Mar 23, 2003
I'd trade it all for just a little more.

I did some reading on wpf, and it looks like quite a mess for what I'm trying to do, but probably a smarter way of doing it.

I ended up spending all evening yesterday trying to figure out and build the control, which is really just a composite control, a panel with a few labels on it, much like an address card view in outlook. I actually ended up pretty happy with it, but wiring up the events was over my head. I got it done, and it works, but I'm sure it's terrible code.

PhonyMcRingRing
Jun 6, 2002

Sprawl posted:

Have you tried the ajax tool kit controls?

http://www.asp.net/ajax/ajaxcontroltoolkit/samples/

Good god, even though that's not what he needed, the ajax toolkit should be avoided like the plague. At work I just replaced a pre-existing menu system that was made up of Ajax Toolkit's Accordion controls and regular ASP's TreeView controls. They were rendering roughly 250k of markup, inline scripts, and inline stylesheets for what should have been a very simple navigation system.

Kekekela
Oct 28, 2004

PhonyMcRingRing posted:

the ajax toolkit should be avoided like the plague

This.

"Just ajaxified the site by using the masterpage to wrap all content in an UpdatePanel!" :suicide:

IratelyBlank
Dec 2, 2004
The only easy day was yesterday
Do any of you guys use F#? I have been reading through this site: http://en.wikibooks.org/wiki/F_Sharp_Programming and following along in VS but it's so different than what I'm used to and a little hard to wrap my head around. It seems really fun, though. I've done a bunch of the problems on http://projecteuler.net using C# and I am going to attempt to go back through and use F# to solve them. Hopefully it will be a good learning experience.

Adbot
ADBOT LOVES YOU

wwb
Aug 17, 2004

^^^nope, but finding an excuse here. I'm reading this book myself and figured out I've been using lots of concepts of functional programming for a while, I just didn't have a name for them . .

  • Locked thread