Solved

Question about classes...

Posted on 2009-04-07
27
226 Views
Last Modified: 2013-12-17
C# .NET 2008 - this is a Windows Based Application with multiple forms.

Hello,

I have a class called AppSecurity that needs to be available in the application at any point in time. I do not need multiple instances of this class - simply one instance. Right now I am instantiating the class from a form. I fear that when I close this form I will end up losing the instance of my class.

Is there a way to create the class so that it does not have to be instantiated? Or is there someplace that I should be instantiating it so that it will be available at all times provided the program is in a runtime state?

Thanks.


0
Comment
Question by:ProWebNetworks
  • 12
  • 9
  • 6
27 Comments
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
Make it in program.cs (as public).
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
Instantiate it there you mean?
0
 
LVL 6

Accepted Solution

by:
Cebik earned 300 total points
Comment Utility

\\Program.cs

using System;

using System.Collections.Generic;

using System.Windows.Forms;
 

namespace WindowsApplication1

{

    static class Program

    {

        /// <summary>

        /// The main entry point for the application.

        /// </summary>

        [STAThread]

        static void Main()

        {

            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);
 

            Application.Run(new Form1());

        }
 

        public static MyClassStatic myStaticClassField;

    }
 

    public static class MyClassStatic

    {

        public int maxLength = 100;

    }

}
 

\\in form

namespace WindowsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            int a = Program.myStaticClassField.maxLength; 
 

            InitializeComponent();

        }

    }

}

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
it's static because you told that you need only one instance per one application..
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Mark the class as static. Then you do not have to instantiate it, but you will lose having member variables.
Definition:
 

public static class Static_Class

{

    public static string Member1 = "some data";

}
 

Implementation:
 

Static_Class.Member1 = "new_data";

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
Why?
public static class MyClassStatic

{

    public int maxLength = 100;

    public byte[] data = null;
 

    public void ReadValue(Stream stream)

    {

        //methode to roead from stream for example

        data = new byte[] { 0, 1, 2 };

    }

}

Open in new window

0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
I guess my only problem is for cleanliness I need the class to remain in a separate file as it is now. Currently I added a class file to the program and named is AppSecurity_Class.cs

Within the program.cs I tried the following:
AppSecurity_Class AppSecurity = new AppSecurity_Class();

But then when I try to reference the class object in my form it tells me it does not exist in the current context. How do I maintain the class in a separate file as it is now, and still use it from program.cs?
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
This class must be static.. because we are puting it in static class & methode..
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
When I try to make the class public static it gives me all kinds of errors telling me:

cannot declare instance members in a static class - it does this with every method, and list object class I am using.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
I'm not sure which IDE you're using Cebik, but 2008 complains about instance members on a static class when I try.
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
Put code of your class..
0
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 200 total points
Comment Utility
You need to mark your members as static as well.
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
This is my class as it is now.
namespace SJRDB_C

{

    public class AppSecurity_Class

    {

        List<int> SecurityList = new List<int>();
 
 

        public int UserLogin(string Username, string Password)

        {

          

            SqlConnection cn = new SqlConnection(PubVar.dbConn);

            cn.Open();
 

            SqlCommand cmd = new SqlCommand(PubVar.dbConn, cn);

            cmd.CommandText = "sp_Login";

            cmd.CommandType = CommandType.StoredProcedure;
 

            SqlParameter param;

            param = cmd.Parameters.AddWithValue("@Username",Username);

            param = cmd.Parameters.AddWithValue("@Password",Password);
 

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

            da.Fill(tbl);
 

            DataRow row;
 

            SqlDataReader rdr = cmd.ExecuteReader();

            

            int LoginSuccess = 0;
 

            while (rdr.Read())

            {

                LoginSuccess++;

            }

            if (LoginSuccess == 1)

            {

                row = tbl.Rows[0];

                PubVar.UserID = Convert.ToInt32(row[0]);

                PubVar.CurrentUser = Convert.ToString(row[1]);

                PubVar.UserDisplayName = Convert.ToString(row[3]) + " " + Convert.ToString(row[4]);
 

               MessageBox.Show(Convert.ToString(PubVar.UserID) + "\n" + PubVar.CurrentUser + "\n" + PubVar.UserDisplayName);
 

            }

            cn.Close();

            cmd.Dispose();

            rdr.Close();

            return (LoginSuccess);

        }
 

        public void CreateSession(int UserID)

        {

            SqlConnection cn = new SqlConnection(PubVar.dbConn);

            cn.Open();
 

            SqlCommand cmd = new SqlCommand(PubVar.dbConn, cn);

            cmd.CommandText = "sp_CreateLoginSession";

            cmd.CommandType = CommandType.StoredProcedure;
 

            SqlParameter param;

            param = cmd.Parameters.AddWithValue("@UserID", PubVar.UserID);
 

            cmd.ExecuteNonQuery();
 
 

        }
 

        public void PopulateSecurityList()

        {

            

            SecurityList.Add(4);

            SecurityList.Add(9);

            SecurityList.Add(10);

        }
 

        public bool CheckSecurity(int SecurityID)

        {

            return SecurityList.Contains(SecurityID);
 

        }

    }

}

Open in new window

0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
From MSDN:

The main features of a static class are:

    *

      They only contain static members.
    *

      They cannot be instantiated.
    *

      They are sealed.
    *

      They cannot contain Instance Constructors (C# Programming Guide).

http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
kaufmed: can you explain me what are you mean? i'm not good english speaking :/ sorry
i've got C# express 2008, and this example works... i made it..and tested..
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
So I had to go thru and add "static" to each method and so forth in my class. I am testing now.

thanks.
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
Sorry for all the confusion guys, I have been studying and reading all about classes and instantiating them etc etc, I guess I hadn't gotten to the static class section in the book yet lol, I didn't even really know they could be used this way.
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
Change it to this... and use like this (without creating filed of this type)
public Form1()
        {
            int a = Program.myStaticClassField.maxLength;

            InitializeComponent();

            bool a = SJRDB_C.AppSecurity_Class.CheckSecurity(2)
        }
namespace SJRDB_C

{

    public static class AppSecurity_Class

    {

        static List<int> SecurityList = new List<int>();

        

        public static int UserLogin(string Username, string Password)

        {
 

            SqlConnection cn = new SqlConnection(PubVar.dbConn);

            cn.Open();
 

            SqlCommand cmd = new SqlCommand(PubVar.dbConn, cn);

            cmd.CommandText = "sp_Login";

            cmd.CommandType = CommandType.StoredProcedure;
 

            SqlParameter param;

            param = cmd.Parameters.AddWithValue("@Username", Username);

            param = cmd.Parameters.AddWithValue("@Password", Password);
 

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable tbl = new DataTable();

            da.Fill(tbl);
 

            DataRow row;
 

            SqlDataReader rdr = cmd.ExecuteReader();
 

            int LoginSuccess = 0;
 

            while (rdr.Read())

            {

                LoginSuccess++;

            }

            if (LoginSuccess == 1)

            {

                row = tbl.Rows[0];

                PubVar.UserID = Convert.ToInt32(row[0]);

                PubVar.CurrentUser = Convert.ToString(row[1]);

                PubVar.UserDisplayName = Convert.ToString(row[3]) + " " + Convert.ToString(row[4]);
 

                MessageBox.Show(Convert.ToString(PubVar.UserID) + "\n" + PubVar.CurrentUser + "\n" + PubVar.UserDisplayName);
 

            }

            cn.Close();

            cmd.Dispose();

            rdr.Close();

            return (LoginSuccess);

        }
 

        public static void CreateSession(int UserID)

        {

            SqlConnection cn = new SqlConnection(PubVar.dbConn);

            cn.Open();
 

            SqlCommand cmd = new SqlCommand(PubVar.dbConn, cn);

            cmd.CommandText = "sp_CreateLoginSession";

            cmd.CommandType = CommandType.StoredProcedure;
 

            SqlParameter param;

            param = cmd.Parameters.AddWithValue("@UserID", PubVar.UserID);
 

            cmd.ExecuteNonQuery();
 
 

        }
 

        public static void PopulateSecurityList()

        {
 

            SecurityList.Add(4);

            SecurityList.Add(9);

            SecurityList.Add(10);

        }
 

        public static bool CheckSecurity(int SecurityID)

        {

            return SecurityList.Contains(SecurityID);
 

        }

    }

}

Open in new window

0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
kaufmed:
I know what are you mean now..
I don't know why it was working before?
Maybe it wasn't... only compiler did not throw error because it was not compiled..

ProWebNetworks:
i think you can prepare this class to be static..
so then you don't have to do anything else only using it directly.. without making object of this class..
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
Statics give you the benefit of not having to instantiate, but be mindful that they consume memory the minute your application is loaded into memory. There is no way to remove a static once it is loaded.
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
This is perfect thank you - it works great!!
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
so solution should be post ID: 24090981
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
Yes, correct, I ended up doing what you put there before you posted it...based on the helpful comments you guys were putting. Then you posted --- post ID: 24090981 and that was dead on what I was asking. I am not sure how to correct the solution.
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
i don't know too :)

kaufmed:
i think that static class is make to to save up free space.
only one class in memory for one application..

you think that better is to create new object every time when you want to use function from them?
Garbage Collector wait some time before hi clean up unused memory...
so he create few instances of this class in memory before hi started to clean old unused object... as i remember..

don't you think that static class is much better?

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
Comment Utility
I was referring more to not marking everything as static. Let's say you have 100 classes all marked static. Every class will reside in memory for the duration of the process' execution.

I am merely saying that one should know when to use static vs. instance.
0
 
LVL 1

Author Comment

by:ProWebNetworks
Comment Utility
This particular class I am pretty sure I needed as static, but did not realize. I can see what you are saying, not everything should be static unless it needs to be referenced throughout. I only have 2 classes that will be static...

PublicVariables or PubVars and my AppSecurity class. Everyother class should be just fine being instantiated within form instances.

Thanks for the good headsup.
0
 
LVL 6

Expert Comment

by:Cebik
Comment Utility
ok..
greetings..
;)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now