Conflicting Objects

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 5854 Views - Last Post: 03 August 2011 - 10:02 AM Rate Topic: -----

#1 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Conflicting Objects

Posted 01 August 2011 - 10:06 AM

Creating a windows forms application using .net 3.5. It communicates with a digital projector via a serial port. I created a Settings class to create objects that essentially keep track of the users proposed changes to the settings.

Here are the objects:

public partial class projectorForm : Form
    {

        private static string comPort = "COM1";
        private SerialPort sp = new SerialPort(comPort, 115200);

        public static Settings defaultSettings = new Settings();
        public static Settings proposedSettings = new Settings();
        public static Settings currentSettings = new Settings();
...
}



Each Settings object keeps track of various settings, such as brightness. If I change the value of brightness in the "proposedSettings" object, for some reason the "currentSettings" brightness value changes as well. This doesn't happen to the "defaultSettings" object.

        private void brightnessSlider_Scroll(object sender, EventArgs e)
        {
            brightnessAmount.Text = "" + brightnessSlider.Value;
            proposedSettings.brightness.value = brightnessSlider.Value; 
          //As soon as the previous line executes, both proposedSettings.brightness.value and currentSettings.brightness.value get changed.
        }



What is going on???

Is This A Good Question/Topic? 0
  • +

Replies To: Conflicting Objects

#2 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 10:18 AM

Why are are making these instances static?

Have you done the same thing with the property inside your Settings class?

That would cause this type of behavior.

Static means there is only one value of that 'thing' shared across instances.

See FAQ #5 for debugging tutorials
See FAQ #6 for Serialization and use of properties.


FAQ (Frequently Asked Questions - Updated July 2011

  • Q: My program doesn't work. I didn't show you any code or actually tell you the error message. How do I fix it?
    Spoiler


  • Q: How do I get Form 'A' to make a change or talk to Form 'B'


  • Q: I'm trying to make a password/login form and...
    A: Password handling tutorial


  • Q: I'm making a client/server chat program and .....
    A:Client/server chat tutorial


  • Q: I do x and y happens which I didn't expect but I don't know how to figure out why. How do I debug and find my problem?


  • Q: I don't understand XML Serialization so I can save my information/class


  • Q:How do I get sound in my program?
    A: Adding sound to your C# application


  • Q: How do I use the serial port?
    A: Serial port communication


  • Q: How do I deploy my program / Make an installer?
    A: C# application deployment project


  • Q: How do I do compression or .zip files?
    A:

  • Q: How do I do multi-threading? Having a problem with cross-threading...


  • Q: I am making a calculator as my school homework project and ...
    A: Calculator tutorial


  • Q: I've been struggling with this for days/weeks and I can't figure it out and my professor is worthless and can't teach. Can someone here explain it to me?
    Spoiler


  • Q: How do I save some information like preferences, settings or other data?


  • Q: I want my textbox to offer suggestions as the user types.
    A: Creating an auto-complete textbox


  • Q: I want to write a program that does x, y and z with features for A, B, and C. {Notice there is no question in this question}
    Spoiler


  • Q: I need to code to do x... Someone tell me the code for y...
    Spoiler


  • Q: What is the best programming language? What programming language should I learn?
    Spoiler


  • Q: How do I get my program to programmatically simulate a mouse click or button press?
    A: Simulate mouse and keystroke (even to another application)


  • Q: I'm not really sure what I want to do with my future? Do you guys like programming? I think I kinda like math and games and computers? What should I do or study?
    A: Get experience while you find yourself


[*]Q: How do I use PInvoke and the Win32 api calls to get functions not available in .NET framework?
A: Using the Win32 API Tutorial

[*]Q: How can I have both a WinForms Windows app, and still have a Console window open?
A: Make your new project a WinForms project. Then go back to project properties (Right-click on the project, select Properties). On the Application tab go to the dropdown that says "Windows Forms" and change it to "Console Application." You know have a WinForms application with a console window. I do this on occassion to see my Console.WriteLine statements when I am debugging. But don't consider this mixed mode operation a proper way to release an application for real-world use.
Was This Post Helpful? 0
  • +
  • -

#3 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4531
  • View blog
  • Posts: 7,903
  • Joined: 08-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 10:18 AM

It's because static means "shared", as in, there's only one copy of a static property across all instances of a class.

Don't use static unless you know you need it.
Was This Post Helpful? 0
  • +
  • -

#4 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Re: Conflicting Objects

Posted 01 August 2011 - 10:52 AM

Thanks for the reply, however I don't believe it's a problem with them being static. They are static because several other classes change their values. Here's my Settings class:

public class Settings
    {
        public Entry brightness;
        public Entry contrast;

        public Entry colorGainRed;
        public Entry colorGainGreen;
        public Entry colorGainBlue;

        public Entry colorOffsetRed;
        public Entry colorOffsetGreen;
        public Entry colorOffsetBlue;

        public Settings()
        {
            brightness = new Entry("BRT", 50);
            contrast = new Entry("CON", 47);

            colorGainRed = new Entry("RCG", 50);
            colorGainGreen = new Entry("GCG", 50);
            colorGainBlue = new Entry("BCG", 50);

            colorOffsetRed = new Entry("RCO", 50);
            colorOffsetGreen = new Entry("GCO", 50);
            colorOffsetBlue = new Entry("BCO", 50);
        }

    }
    public class Entry
    {
        public string code = "";
        public int value = 0;

        public Entry(string Code, int Value)
        {
            code = Code;
            value = Value;
        }
    }



So each instance should have its own set of properties. I *did* run a debug on it. See original post. That exact line is where both values change. That line does not call another method.

We could get into whether or not the properties should be public or private with getter/setter methods, which is how I realize it probably should be done, but I don't *think* that's causing the problem at the moment.

This post has been edited by Elliotd123: 01 August 2011 - 10:53 AM

Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 11:18 AM

View PostElliotd123, on 01 August 2011 - 11:52 AM, said:

They are static because several other classes change their values.


That is in NO WAY a valid reason for them to be static, nor the right way to allow access to them from other classes.

The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Separating data from GUI - PLUS - serializing the data to XML
Passing values between forms/classes
Was This Post Helpful? 1
  • +
  • -

#6 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Re: Conflicting Objects

Posted 01 August 2011 - 11:36 AM

Ok, they're not static anymore. Same problem. Instead of having them be static, I passed the Settings to the other classes as a parameter. No change in how the program works though.

This post has been edited by Elliotd123: 01 August 2011 - 11:38 AM

Was This Post Helpful? 0
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 11:40 AM

I'm building a simple test project to confirm something. So bear with me.

But I'm going to guess that since you ahve several other classes reading and writting here that you have some loop you are unware of reacting to a change and setting the other values.

Back in a sec
Was This Post Helpful? 0
  • +
  • -

#8 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Re: Conflicting Objects

Posted 01 August 2011 - 11:42 AM

If that were the case, wouldn't the debugger step into said loop?
Was This Post Helpful? 0
  • +
  • -

#9 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Re: Conflicting Objects

Posted 01 August 2011 - 11:55 AM

Ok I may be getting somewhere here. It's probably because I don't understand how C# compares objects...I have a statement that goes:

proposedSettings = currentSettings;



I'm guessing that in C# this does weird things with the two. If I comment this out, the problem goes away, so I'm assuming that C# doesn't make a copy, and instead assigns the same memory address to both objects? If that were the case then after this statement they would be the same thing.
Was This Post Helpful? 1
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 11:57 AM

Ya know how you can know something, yet doubt it anyway? I had one of those moments. I just had to make sure that your 3 static classes weren't in some way acting as one.

So I ran up a quick test app that makes a class, then makes 3 static instances just like you've done but simplified.

Spoiler


When run this confirmed what we all knew: That the three static classes were indeed separate from each other and do not cause each other to interact. If they had, we would have seen the lower textboxes here change to match the values of the two upper ones. That didn't happen.

Attached Image

So I have to go back to my recent comment that your multiple classes are interacting in a way you didn't intend, and bouncing the new value into the other instances.

You should be able to see this happening if you put a breakpoint within the set method of a property then look at the call to see which methods were called to get to that point.

Attached Image
Was This Post Helpful? 0
  • +
  • -

#11 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 12:07 PM

Quote

Ok I may be getting somewhere here. It's probably because I don't understand how C# compares objects...I have a statement that goes:


proposedSettings = currentSettings;



I'm guessing that in C# this does weird things with the two. If I comment this out, the problem goes away, so I'm assuming that C# doesn't make a copy, and instead assigns the same memory address to both objects? If that were the case then after this statement they would be the same thing.


That's not a comparrison. You are setting the left hand object to be the right hand object. Nothing weird about this.

int a = 1;
string Yogi = "Bear";
Settings propsosedSettings = currentSettings;

This post has been edited by tlhIn`toq: 01 August 2011 - 12:10 PM

Was This Post Helpful? 0
  • +
  • -

#12 Elliotd123  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 24-January 11

Re: Conflicting Objects

Posted 01 August 2011 - 12:11 PM

Yeah that was the problem. Since I'm not a huge C# programmer (Although I like the language), I didn't realize that C# doesn't make a COPY of an object when you do that, it just sets them both to the same memory location. As a result, changing one will thereafter change the other one. I fixed this problem by creating a copy constructor in the Settings class, and then invoking that constructor when assigning the new settings.

proposedSettings = new Settings(currentSettings);



Now it works like a charm. Thanks guys. And thank you also for the advice on static modifiers.
Was This Post Helpful? 2
  • +
  • -

#13 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 12:14 PM

If you aren't sure how C# does these sorts of things then I can only assume C# is new to you. ??

Let me make the same suggestion I make 20 times a week here: Don't try to make a project from scratch for a useful purpose, as your learning project. You're still learning the language and syntax. You don't yet know enough to design and architect a solution if you don't understand how basics like classes and assignments work.

If you come from a different language then you should be able to easily breeze through a few introductory tutorials because you only need to learn the differences in the coding languages and not the entire concept behind them.


Standard resources, references and suggestions for new programmers. - Updated July 2011

Don't try to create a useful working program to fit a need of yours (or a for-pay contract) as your introduction to coding project. When you are learning to code you don't know enough to code a program, let alone know how to engineer the architecture of a program. It would be like saying "I don't know how to read sheet music, or play an instrument. I think I'll write a 3 act opera as my first learning experience."

The problem with taking on large, complex tasks when you are new to coding is that
  • It will frustrate you to the point of quitting. We don't want you to quit. We want you to succeed and learning how to code and engineer software.
  • You don't know enough about coding to know where to start or in what direction to design your program
  • You risk learning via the 'Swiss cheese' method where you only learn certain bits and pieces for the one project but have huge holes in your education.


Finding answers to specific problems:
Sometimes just knowing where to look can make all the difference. Google is your friend.
Search with either "C#" or "MSDN" as the first word: "MSDN Picturebox", "C# Custom Events", "MSDN timer" etc.
How to do a good search that will get you targeted answers.

Don't think you are the first person to ask a question. Try a search on this site to see if someone has already brought up this problem. Also, as soon as you post your question go to the bottom of the updated page: You will see where the system has already analyzed your question and tried to find similar threads for the same question, so check those links out.

But honestly, just typing away and seeing what pops up in Intellisense is going to make your self-education take 20 years. You can learn by trying to reverse engineer the language through banging on the keyboard experimentation - or you can learn by doing the tutorials and following a good "How to learn C#" book. There are so many great "How do I build my first application" tutorials on the web... There are dozens of "Learn C# in 21 days", "My first C# program" type books at your local book seller or even public library.

Beginner:
Build a Program Now! in Visual C# by Microsoft Press, ISBN 0-7356-2542-5
is a terrific book that has you build a Windows Forms application, a WPF app, a database application, your own web browser.

Visual Studio Keyboard Shortcuts


D.I.C. C# Resource page Start here
Intro to C# online tutorial then here...
C# control structures then here.
MSDN Beginner Developer video series
MSDN video on OOP principals, making classes, constructors, accessors and method overloading
MSDN Top guideline violations, know what to avoid before you do it.
Design patterns as diagrams

I hate sending people to another site when we have such good tutorials here, but this series shouldn't be overlooked.
Programming OOP in C# - Part 1
Programming OOP in C# - Part 2
Programming OOP in C# - Part 3
Programming OOP in C# - Part 4
Programming OOP in C# - Part 5

Writing a text file is always one of the first things people want to do, in order to store data like high-scores, preferences and so on
Writing a text file tutorial.
Reading a text file tutorial.

Have you seen the 500+ MSDN Code Samples? They spent a lot of time creating samples and demos. It seems a shame to not use them.

Intermediate:
The tutorials below walk through making an application including inheritance, custom events and custom controls, object serialization and more.
Bulding an application - Part 1
Building an application - Part 2
Quick and easy custom events
Separating data from GUI - PLUS - serializing the data to XML
Passing values between forms/classes

Working with environmental variables
'Why do we use delegates?' thread

And everyone always wants to connect to a database, right out of the gate so
Database tutorials right here on DIC

C# Cookbooks
Are a great place to get good code, broken down by need, written by coding professionals. You can use the code as-is, but take the time to actually study it. These professionals write in a certain style for a reason developed by years of experience and heartache.

Everyone:
Debugging tutorial
Debugging tips
Debugging in detail
Great debugging tips
It still doesn't work, article
Momerath is right about learning to work on the basics before you try to create your own assignments or program ideas.

We don't say this to be mean. We've seen lots of new coders take this approach and we know it doesn't work. Trying to design your own programs before you understand the basics of the code language you've chosen just leads to problems, frustrations, and 'swiss-cheese' education (lots of holes).

I urge you to work through the C# learning series here on DIC, and to work a self-teaching book from cover to cover before you even think about designing your own applications.


Microsoft Visual Studio Tips, 251 ways to improve your productivity, Microsoft press, ISBN 0-7356-2640-5
Has many, many great, real-world tips that I use all the time.

These are just good every-day references to put in your bookmarks.
MSDN C# Developers Center with tutorials
Welcome to Visual Studio
Free editions of Visual Studio 2010

Let me also throw in a couple tips:
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.

  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.
    btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)

  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like Index, TimeOut, Row, Column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.

  • Learn how to search the 'net for examples.
    How to do a good search that will get you targeted answers.

  • Try to avoid having work actually take place in GUI control event handlers. It is usually better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    btnSave(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveMenuItem(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    SaveContextMenu(object sender, eventargs e)
    {
        SavePreferences();
    }
    
    FormMain_Closing(object sender, eventargs e)
    {
        if (IsDirty) SavePreferences();
    }
    


  • This can't be stressed enough in today's world of cell phone messaging:
    Don't use txt/sms/leet/T9 speak like: u no, u r, dnt, wut i m do-n, coz, al gud, b4, ny1, and so on. like this guy:

    dis not b d'hood dawg... You are sitting at a real keyboard with a real monitor, not a cell phone. You are not here texting your high school posse to come to your kegger after their shift at Taco Bell. You are here asking for help from senior coding professionals who graciously donate their valuable time to helping the next generation of coders with their chosen craft. Please try to show them, yourself and the industry some respect by writing at least at an eighth grade level. (IE: English not ebonics or SMS, real words, punctuation and so on). If you can't take your own problem/question seriously enough to write like an adult, then why would you expect anyone else to take it seriously?

  • I strongly suggest installing VMware or some other virtualization technology on your development PC so you can create a couple virtual computers for testing. This would allow you to debug and test inside: WinXP32, XP64, Vista, Win7x32, Win7x64... etc. without having to actually have 5 physical PC's. Visual Studio will let you send the debug directly into one of these virtual machines so you can watch it operate, check its variables, see the crashes and so on just as if it were debugging on your real machine.

Was This Post Helpful? 0
  • +
  • -

#14 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Conflicting Objects

Posted 01 August 2011 - 12:15 PM

Good thread all around, make it rain karma in this one. :)

Posted Image
Was This Post Helpful? 0
  • +
  • -

#15 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5582
  • View blog
  • Posts: 11,941
  • Joined: 02-June 10

Re: Conflicting Objects

Posted 01 August 2011 - 12:17 PM

View PostElliotd123, on 01 August 2011 - 01:11 PM, said:

Yeah that was the problem. Since I'm not a huge C# programmer (Although I like the language), I didn't realize that C# doesn't make a COPY of an object when you do that, it just sets them both to the same memory location. As a result, changing one will thereafter change the other one. I fixed this problem by creating a copy constructor in the Settings class, and then invoking that constructor when assigning the new settings.

proposedSettings = new Settings(currentSettings);



Now it works like a charm. Thanks guys. And thank you also for the advice on static modifiers.


Glad we could help. And welcome to C#. I hope to be seeing a lot more of you in this topic area. It's nice to see someone new that makes an effort and seems to have a grasp on it.

Don't forget, we're all volunteers. So if anyone in any question gives you helpful advice, that little green + is a great way to say "Thanks"
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2