Solved

Question about classes...

Posted on 2009-04-07
27
237 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 9
  • 6
27 Comments
 
LVL 6

Expert Comment

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

Author Comment

by:ProWebNetworks
ID: 24090656
Instantiate it there you mean?
0
 
LVL 6

Accepted Solution

by:
Cebik earned 300 total points
ID: 24090748

\\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
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 6

Expert Comment

by:Cebik
ID: 24090775
it's static because you told that you need only one instance per one application..
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24090779
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
ID: 24090825
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
ID: 24090828
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
ID: 24090862
This class must be static.. because we are puting it in static class & methode..
0
 
LVL 1

Author Comment

by:ProWebNetworks
ID: 24090864
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 75

Expert Comment

by:käµfm³d 👽
ID: 24090865
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
ID: 24090867
Put code of your class..
0
 
LVL 75

Assisted Solution

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

Author Comment

by:ProWebNetworks
ID: 24090895
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
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 24090897
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
ID: 24090901
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
ID: 24090937
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
ID: 24090970
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
ID: 24090981
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
ID: 24091019
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 75

Expert Comment

by:käµfm³d 👽
ID: 24091023
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
ID: 24091033
This is perfect thank you - it works great!!
0
 
LVL 6

Expert Comment

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

Author Comment

by:ProWebNetworks
ID: 24091071
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
ID: 24091152
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 75

Expert Comment

by:käµfm³d 👽
ID: 24091193
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
ID: 24091235
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
ID: 24091285
ok..
greetings..
;)
0

Featured Post

Online Training Solution

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action. Forget about retraining and skyrocket knowledge retention rates.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.net/VSTO Excel Add-in 2 38
Visual Studio 2015 auto inserted code 12 88
Building an object from several other objects 4 39
search by any word in column 5 29
We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

732 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