[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 245
  • Last Modified:

Question about classes...

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
ProWebNetworks
Asked:
ProWebNetworks
  • 12
  • 9
  • 6
2 Solutions
 
CebikCommented:
Make it in program.cs (as public).
0
 
ProWebNetworksAuthor Commented:
Instantiate it there you mean?
0
 
CebikCommented:

\\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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
CebikCommented:
it's static because you told that you need only one instance per one application..
0
 
käµfm³d 👽Commented:
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
 
CebikCommented:
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
 
ProWebNetworksAuthor Commented:
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
 
CebikCommented:
This class must be static.. because we are puting it in static class & methode..
0
 
ProWebNetworksAuthor Commented:
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
 
käµfm³d 👽Commented:
I'm not sure which IDE you're using Cebik, but 2008 complains about instance members on a static class when I try.
0
 
CebikCommented:
Put code of your class..
0
 
käµfm³d 👽Commented:
You need to mark your members as static as well.
0
 
ProWebNetworksAuthor Commented:
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
 
käµfm³d 👽Commented:
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
 
CebikCommented:
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
 
ProWebNetworksAuthor Commented:
So I had to go thru and add "static" to each method and so forth in my class. I am testing now.

thanks.
0
 
ProWebNetworksAuthor Commented:
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
 
CebikCommented:
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
 
CebikCommented:
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
 
käµfm³d 👽Commented:
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
 
ProWebNetworksAuthor Commented:
This is perfect thank you - it works great!!
0
 
CebikCommented:
so solution should be post ID: 24090981
0
 
ProWebNetworksAuthor Commented:
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
 
CebikCommented:
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
 
käµfm³d 👽Commented:
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
 
ProWebNetworksAuthor Commented:
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
 
CebikCommented:
ok..
greetings..
;)
0

Featured Post

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

  • 12
  • 9
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now