Question

Serializing a Static Object in C#

Asked by: duerra

I can't seem to find anything that is helping me out on this one anywhere on the net.

I have an object that consists of only static data.  I do not initialize any instance of the class except within the class itself.  However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).

All references I can find show example of creating a new instance of an object, then serializing that.  Instead of creating a new instance of an object, how can I just serialize all the static values of the class, and then deserialize them back into the class?

Thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-10-20 at 16:19:10ID21176423
Tags

deserialize

Topic

C# Programming Language

Participating Experts
2
Points
0
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. serialization and deserialization
    How do you go about serialization and deserialization of the Airplane Class ? We are still not doing objects in class which is why I am asking this question , :JIM YOU THERE :-): From the problem description, several classes jumped out at me: Airplane, SeatingClass, Seat, a...
  2. How to serialize an GUI and deserialize it at the other end...
    Could anyone show me the source code (and steps) of serialize a GUI and deserialize it at the remote client application??? Does this task involves some kind of class loader??? thanks. stephen

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: knowltonPosted on 2004-10-20 at 17:30:09ID: 12364994

I am new to C#.  I may not be able to help...but sometimes talking through a problem helps lead to an answer.

Can you post your class code....and explain what you mean by static data and serializing public values?

My understanding is that static data are values that are tracked among several instances of the same class.  This allows you to count how many instances you have created, etc.    Is that correct?

Also...it is just your data members, not methods that are static?

I have a book on C# which states:  "Static methods do not require an instance of an object and, therefore, cannot access the data members of the current class."

 

by: knowltonPosted on 2004-10-20 at 17:38:33ID: 12365101

I created a quick Windows App to test static data members:



using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplicationStaticSerialization
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  TestStatic ts = new TestStatic();
                  MessageBox.Show(ts.longVar.ToString());
                  
            }
      }

      public class TestStatic
      {
            public static long longVarStatic;
            public long longVar;

            public TestStatic()
            {
                  MessageBox.Show("hi from test static");
                  longVar = 5;
            }
      }
}



=================================================

The output is:

hi from test static

5


==================================================

The variable that I declared static did NOT show up as accessible by the ts object!!!!!  I am not sure why this is.

 

by: knowltonPosted on 2004-10-20 at 17:48:21ID: 12365160

As I gained more understanding I modified my code as follows:


using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

namespace WindowsApplicationStaticSerialization
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  TestStatic ts = new TestStatic();
                  TestStatic ts_2 = new TestStatic();            
                  TestStatic ts_3 = new TestStatic();            
                  TestStatic ts_4 = new TestStatic();            
                  TestStatic ts_5 = new TestStatic();            
                  TestStatic ts_6 = new TestStatic();            
                  MessageBox.Show("After 6 instances of TestStatic, count is:  " + ts_6.OutputStaticVarValue().ToString());
            }
      }

      public class TestStatic
      {
            public static long longVarStatic=0;
            public long longVar;

            public TestStatic()
            {                        
                  longVarStatic++;                  
            }

            public long OutputStaticVarValue()
            {
                  return longVarStatic;
            }

      }
}


============================================================


Here is the output:


After 6 instances of TestStatic, count is:  6



So the value of the static data member called longVarStatic is preserved as each instance is created!!!!!!



I know this is basic stuff to you.....I am just trying to understand what you are asking.  :)   Please bear with me.  :)

 

by: knowltonPosted on 2004-10-20 at 17:51:54ID: 12365177

<quote>
 I can't seem to find anything that is helping me out on this one anywhere on the net.

I have an object that consists of only static data.  I do not initialize any instance of the class except within the class itself.  However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).

All references I can find show example of creating a new instance of an object, then serializing that.  Instead of creating a new instance of an object, how can I just serialize all the static values of the class, and then deserialize them back into the class?

</quote>


>>>I have an object that consists of only static data.

Okay, now I understand what that means.  :)


>>>I do not initialize any instance of the class except within the class itself

Hmmmm.....you may have to show me how you do this....I'll see what I can come up with....

 

by: knowltonPosted on 2004-10-20 at 17:56:04ID: 12365195

>>>I do not initialize any instance of the class except within the class itself

Ohhhhh.....so you mean you DO NOT do things like this:

TestStatic ts = new TestStatic(<value one>, <value two>);    //HERE.....the object is being initialized with values passed in.

Is that what you mean?


So you only do this:

TestStatic ts = new TestStatic( );  //Here there is no initialization taking place.....except what the constructor may be doing....that is to say....no values are passed in or accepted.

 

by: knowltonPosted on 2004-10-20 at 17:57:13ID: 12365201

I guess I am stuck on this part now:

>>>>>However, I need to serialize the public or accessible values of this class, and then load them up again (back into the static object).

 

by: knowltonPosted on 2004-10-20 at 18:00:34ID: 12365212

From another post here in EE I learned what serialization is:

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_20689551.html?query=serialize&topics=327:

DEFINITION
It is the process of converting an object (an instance of a class) into a stream of bytes which can be passed over a network, and re-assembled at the other end.. or written to a file for later retrieval.


I will proceed based on this definition.

 

by: knowltonPosted on 2004-10-20 at 18:13:03ID: 12365284

Okay.....here is some working code for a Windows Form that demonstrates serialization:

Taken from this online tutorial:  http://www.ondotnet.com/pub/a/dotnet/2002/08/26/serialization.html?page=1


[[NOTE:  Just create a new C# Windows Application.  Replace the skeleton code that C# generates with THIS code.  Compile and run the application.  Should work]]

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;


namespace MyCSharp
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.MainMenu mainMenu1;
            private System.Windows.Forms.MenuItem fileMenuItem;
            private System.Windows.Forms.MenuItem fileNewMenuItem;
            private System.Windows.Forms.MenuItem fileOpenMenuItem;
            private System.Windows.Forms.MenuItem fileSaveMenuItem;
            private System.Windows.Forms.MenuItem fileSaveAsMenuItem;
            private System.Windows.Forms.MenuItem fileExitMenuItem;
            private System.Windows.Forms.ToolBar toolBar1;
            private System.Windows.Forms.ToolBarButton lineToolBarButton;
            private System.Windows.Forms.ToolBarButton rectangleToolBarButton;
            private System.Windows.Forms.ToolBarButton ellipseToolBarButton;
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.Container components = null;

            private ArrayList shapes = new ArrayList();
            private enum shapeType
            {
                  line, rectangle, ellipse,
            }

            private shapeType drawnShapeType = shapeType.line;
            private Point startPoint;
            private String filename;

            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }

            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  if( disposing )
                  {
                        if (components != null)
                        {
                              components.Dispose();
                        }
                  }
                  base.Dispose( disposing );
            }

            #region Windows Form Designer generated code
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                  this.mainMenu1 =
                        new System.Windows.Forms.MainMenu();
                  this.fileMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileNewMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileOpenMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileSaveMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileSaveAsMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.fileExitMenuItem =
                        new System.Windows.Forms.MenuItem();
                  this.toolBar1 =
                        new System.Windows.Forms.ToolBar();
                  this.lineToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.rectangleToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.ellipseToolBarButton =
                        new System.Windows.Forms.ToolBarButton();
                  this.SuspendLayout();
                  //
                  // mainMenu1
                  //
                  this.mainMenu1.MenuItems.AddRange(
                        new System.Windows.Forms.MenuItem[] {
                                                                                    this.fileMenuItem});
                  //
                  // fileMenuItem
                  //
                  this.fileMenuItem.Index = 0;
                  this.fileMenuItem.MenuItems.AddRange(
                        new System.Windows.Forms.MenuItem[] {
                                                                                    this.fileNewMenuItem,
                                                                                    this.fileOpenMenuItem,
                                                                                    this.fileSaveMenuItem,
                                                                                    this.fileSaveAsMenuItem,
                                                                                    this.fileExitMenuItem});
                  this.fileMenuItem.Text = "File";
                  //
                  // fileNewMenuItem
                  //
                  this.fileNewMenuItem.Index = 0;
                  this.fileNewMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlN;
                  this.fileNewMenuItem.Text =
                        "&New";
                  this.fileNewMenuItem.Click +=
                        new System.EventHandler(this.fileNewMenuItem_Click);
                  //
                  // fileOpenMenuItem
                  //
                  this.fileOpenMenuItem.Index = 1;
                  this.fileOpenMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlO;
                  this.fileOpenMenuItem.Text =
                        "&Open";
                  this.fileOpenMenuItem.Click +=
                        new System.EventHandler(this.fileOpenMenuItem_Click);
                  //
                  // fileSaveMenuItem
                  //
                  this.fileSaveMenuItem.Index = 2;
                  this.fileSaveMenuItem.Shortcut =
                        System.Windows.Forms.Shortcut.CtrlS;
                  this.fileSaveMenuItem.Text = "&Save";
                  this.fileSaveMenuItem.Click +=
                        new System.EventHandler(this.fileSaveMenuItem_Click);
                  //
                  // fileSaveAsMenuItem
                  //
                  this.fileSaveAsMenuItem.Index = 3;
                  this.fileSaveAsMenuItem.Text = "Save &As";
                  this.fileSaveAsMenuItem.Click +=
                        new System.EventHandler(this.fileSaveAsMenuItem_Click);
                  //
                  // fileExitMenuItem
                  //
                  this.fileExitMenuItem.Index = 4;
                  this.fileExitMenuItem.Text = "E&xit";
                  this.fileExitMenuItem.Click +=
                        new System.EventHandler(this.fileExitMenuItem_Click);
                  //
                  // toolBar1
                  //
                  this.toolBar1.Buttons.AddRange(
                        new System.Windows.Forms.ToolBarButton[] {
                                                                                           this.lineToolBarButton,
                                                                                           this.rectangleToolBarButton,
                                                                                           this.ellipseToolBarButton});
                  this.toolBar1.DropDownArrows = true;
                  this.toolBar1.Name = "toolBar1";
                  this.toolBar1.ShowToolTips = true;
                  this.toolBar1.Size = new System.Drawing.Size(292, 39);
                  this.toolBar1.TabIndex = 0;
                  this.toolBar1.ButtonClick +=
                        new System.Windows.Forms.ToolBarButtonClickEventHandler(
                        this.toolBar1_ButtonClick);
                  //
                  // lineToolBarButton
                  //
                  this.lineToolBarButton.Text = "Line";
                  //
                  // rectangleToolBarButton
                  //
                  this.rectangleToolBarButton.Text = "Rectangle";
                  //
                  // ellipseToolBarButton
                  //
                  this.ellipseToolBarButton.Text = "Ellipse";
                  //
                  // Form1
                  //
                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
                  this.BackColor = System.Drawing.Color.White;
                  this.ClientSize = new System.Drawing.Size(292, 273);
                  this.Controls.AddRange(
                        new System.Windows.Forms.Control[] {
                                                                                 this.toolBar1});
                  this.Menu = this.mainMenu1;
                  this.Name = "Form1";
                  this.Text = "Form1";
                  this.MouseDown +=
                        new System.Windows.Forms.MouseEventHandler(this_MouseDown);
                  this.MouseUp +=
                        new System.Windows.Forms.MouseEventHandler(this_MouseUp);
                  this.ResumeLayout(false);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                  Application.Run(new Form1());
            }

            private void fileExitMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  this.Close();
            }

            private void toolBar1_ButtonClick(object sender,
                  System.Windows.Forms.ToolBarButtonClickEventArgs e)
            {
                  if (e.Button==lineToolBarButton)
                        drawnShapeType = shapeType.line;
                  else if (e.Button==rectangleToolBarButton)
                        drawnShapeType = shapeType.rectangle;
                  else
                        drawnShapeType = shapeType.ellipse;
            }

            private void fileNewMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  shapes.Clear();
                  this.CreateGraphics().Clear(Color.White);
            }

            private void fileOpenMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  OpenDocument();
            }

            private void fileSaveMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  Save();
            }

            private void fileSaveAsMenuItem_Click(object sender,
                  System.EventArgs e)
            {
                  SaveAs();
            }

            private void OpenDocument()
            {
                  OpenFileDialog openFileDialog = new OpenFileDialog();

                  if (openFileDialog.ShowDialog() == DialogResult.OK)
                  {
                        filename = openFileDialog.FileName;
                        Stream myStream = openFileDialog.OpenFile();
                        if (myStream != null)
                        {
                              IFormatter formatter = new BinaryFormatter();
                              shapes = (ArrayList) formatter.Deserialize(myStream);
                              myStream.Close();
                              this.Refresh();
                        }
                  }
            }

            private bool Save()
            {
                  if (filename==null)
                  {
                        return SaveAs();
                  }
                  else
                  {
                        Stream myStream ;
                        myStream = File.OpenWrite(filename);
                        if (myStream != null)
                        {
                              IFormatter formatter =
                                    /*(IFormatter) */ new BinaryFormatter();
                              // serialize shapes
                              formatter.Serialize(myStream, shapes);
                              myStream.Close();
                              return true;
                        }
                  }
                  return false;
            }

            private bool SaveAs()
            {
                  SaveFileDialog saveFileDialog = new SaveFileDialog();
                  if (saveFileDialog.ShowDialog() == DialogResult.OK)
                  {
                        filename = saveFileDialog.FileName;
                        return Save();
                  }
                  return false;
            }

            private void this_MouseDown(object sender,
                  System.Windows.Forms.MouseEventArgs e)
            {
                  if (e.Button==System.Windows.Forms.MouseButtons.Left)
                  {
                        startPoint = new Point(e.X, e.Y);
                  }
            }

            override protected void OnPaint(
                  System.Windows.Forms.PaintEventArgs e)
            {
                  Graphics g = e.Graphics;
                  IEnumerator shapeEnum = shapes.GetEnumerator();
                  while (shapeEnum.MoveNext())
                  {
                        IShape shape = (IShape) shapeEnum.Current;
                        shape.Draw(g);
                  }
            }

            private void this_MouseUp(object sender,
                  System.Windows.Forms.MouseEventArgs e)
            {
                  if (e.Button==System.Windows.Forms.MouseButtons.Left)
                  {
                        Point endPoint = new Point(e.X, e.Y);
                        if (drawnShapeType==shapeType.line)
                        {
                              shapes.Add(new Line(startPoint, endPoint));
                        }
                        else if (drawnShapeType==shapeType.rectangle)
                        {
                              shapes.Add(new Rect(GetRectangleFromPoints(startPoint,
                                    endPoint)));
                        }
                        else
                        {
                              shapes.Add(new Ellipse(GetRectangleFromPoints(startPoint,
                                    endPoint)));
                        }
                  }
                  this.Refresh();
            }

            private Rectangle GetRectangleFromPoints(Point p1, Point p2)
            {
                  int x1, x2, y1, y2;
                  if (p1.X < p2.X)
                  {
                        x1 = p1.X;
                        x2 = p2.X;
                  }
                  else
                  {
                        x1 = p2.X;
                        x2 = p1.X;
                  }

                  if (p1.Y < p2.Y)
                  {
                        y1 = p1.Y;
                        y2 = p2.Y;
                  }
                  else
                  {
                        y1 = p2.Y;
                        y2 = p1.Y;
                  }
                  // x2 > x1 and y2 > y1
                  return new Rectangle(x1, y1, x2 - x1, y2 - y1);
            }

      }
}

namespace MyCSharp
{
      public interface IShape
      {
            void Draw(Graphics g);
      }

      [Serializable]
      public class Line : IShape
      {
            Point startPoint, endPoint;
            public Line(Point startPoint, Point endPoint)
            {
                  this.startPoint = startPoint;
                  this.endPoint = endPoint;
            }
            public void Draw(Graphics g)
            {
                  g.DrawLine(Pens.Black, startPoint, endPoint);
            }
      }

      [Serializable]
      public class Rect : IShape
      {
            Rectangle rect;
            public Rect(Rectangle rect)
            {
                  this.rect = rect;
            }
            public void Draw(Graphics g)
            {
                  g.DrawRectangle(Pens.Black, rect);
            }
      }

      [Serializable]
      public class Ellipse : IShape
      {
            Rectangle rect;
            public Ellipse(Rectangle rect)
            {
                  this.rect = rect;
            }
            public void Draw(Graphics g)
            {
                  g.DrawEllipse(Pens.Black, rect);
            }
      }

}

 

by: duerraPosted on 2004-10-20 at 18:38:04ID: 12365468

knowlton, just... stop.  Your 20 posts of whatever are not helping me in any way.



Consider the following class:

      public class Test
      {
            private static int testint = 1;

            public static int TestInt
            {
                  get
                  {
                        return testint;
                  }
                  set
                  {
                        testint = value;
                  }
            }
      }



This class provides only static methods for accessing variables.
Therefore, the following declaration is not valid:

Test mytest = new Test();

I need to take all the publically available values of the class "Test" (in this case, only testint, through TestInt property), and serialize them, even though there is no instance of the object.  I also need to be able to reload the serialized variables into the static class at another point in time, obviously.

I hope this clarifies.

 

by: duerraPosted on 2004-10-20 at 19:00:37ID: 12365801

Nevermind.  I figured out a working solution.

For other users out there, look into Singleton patterns.  It's not really possible (as far as I'm aware), to serialize a non-instantiated object, but if you force instantiation, then simply have the instance return a static instance of the object, it works out.....

 

by: knowltonPosted on 2004-10-21 at 08:15:13ID: 12370918

Beautiful!!!  Glad you found an answer, and I received quite an education just trying to understand the QUESTION!!!!  :)

Recommend mark this as PAQ and get your points refunded.

Tom

 

by: knowltonPosted on 2004-11-16 at 07:35:22ID: 12594636

No objections, here.

 

by: moduloPosted on 2004-11-20 at 01:11:36ID: 12632841

PAQed with points refunded (350)

modulo
Community Support Moderator

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...