none
when using static classes or function and why ? RRS feed

  • Question

  • when i need to make some module or app on visual studio 2017 csharp i put all function as public on class 

    as following

     public class AnnualMember
        {
        }

    and inside it i using function as public as 

    public void Deletemembers()
    {
    }

    I dont use static before and i dont make static function or classes before

    can you tell me if possible when and why i using static classes or functions

    which cases please i use that

    Tuesday, April 2, 2019 3:18 AM

Answers

  • One uses a  static class when it doesn't need to be instanced into an object, and a method on the static class can just be called, like you see the Application_Start. Each static class's method is called in the start-up process on each usage of the Web application. Web applications are stateless. meaning that  it doesn't  run and stay in state continuously in memory, unlike a Windows desktop program

    And each time the Web program  is used by a user, which could be 50 times in a user session  a single user session, the program  goes through the startup process. If the program had to use the 'new' keyword to instance the classes/objects, it would slow the Web program down on the startup process.

    One can use static classes for utility or helper things that are global to the application where any code anywhere that can see the static class can use it.

    It doesn't mean that you go hog-wild and start using static classes all over the place, like I have seen developers do, but you should know when static class will be an advantageous usage.

    But in general, one uses static classes in a program startup, as a utility class or as a helper class.

    using System.IO;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using MVC.App_Start;
    
    namespace MVC
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                UnityMVC5.Start();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
            }
        }
    }

    using System.Data;
    using System.Data.Common;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.Owin.Security;
    using Microsoft.Practices.Unity;
    using Unity.Mvc5;
    using ServiceLayer;
    using WebAPI.Controllers;
    using MVC.Models;
    
    
    namespace MVC.App_Start
    {
        public static class IocExtensions
        {
            public static void BindInRequestScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new HierarchicalLifetimeManager());
            }
    
            public static void BindInSingletonScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new ContainerControlledLifetimeManager());
            }
        }
    
        public class UnityMVC5
        {
            public static void Start()
            {
                var container = BuildUnityContainer();
                DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            }
    
            private static IUnityContainer BuildUnityContainer()
            {
                var container = new UnityContainer();
    
                //Models
                container.BindInRequestScope<IStudentModels, StudentModels>();
                container.BindInRequestScope<IEnrollmentModels, EnrollmentModels>();
    
                //SeviceLayer
                container.BindInRequestScope<IServiceA, ServiceA>();
    
                //WebAPI controllers
                container.BindInRequestScope<IStudentControllerAPI, StudentController>();
                container.BindInRequestScope<IEnrollmentControllerAPI, EnrollmentController>();
    
                //asp.net idenity
    
                container.RegisterType<ApplicationDbContext>();
                container.RegisterType<ApplicationSignInManager>();
                container.RegisterType<ApplicationUserManager>();
                container.RegisterType<IAuthenticationManager>(
                                 new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
                container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                            new InjectionConstructor(typeof(ApplicationDbContext)));
    
                return container;
            }
        }
    }


    Tuesday, April 2, 2019 6:11 AM

All replies

  • The best example of how to use static is the Math class. None of the methods - like Max, Min, Cos, Sin - need an instance of the class to work, so they are all static. Also, constants like Pi and e never change, so there is no need for an instance of the class to access them, and they can be static too.

    Tuesday, April 2, 2019 5:06 AM
  • In addition to your reply, static variables is often created when you have some global settings to store affecting behaviour of all static methods (or even instance methods).

    The other use of it is to implement singleton design pattern.

    Tuesday, April 2, 2019 5:36 AM
    Answerer

  • Hi 

    Thank you for posting here.

    Based on your description, you want to know when and why to use static classes or static functions.

    You could refer to the following link to understand it.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

     

    Best regards,

    Jack 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, April 2, 2019 6:00 AM
    Moderator
  • One uses a  static class when it doesn't need to be instanced into an object, and a method on the static class can just be called, like you see the Application_Start. Each static class's method is called in the start-up process on each usage of the Web application. Web applications are stateless. meaning that  it doesn't  run and stay in state continuously in memory, unlike a Windows desktop program

    And each time the Web program  is used by a user, which could be 50 times in a user session  a single user session, the program  goes through the startup process. If the program had to use the 'new' keyword to instance the classes/objects, it would slow the Web program down on the startup process.

    One can use static classes for utility or helper things that are global to the application where any code anywhere that can see the static class can use it.

    It doesn't mean that you go hog-wild and start using static classes all over the place, like I have seen developers do, but you should know when static class will be an advantageous usage.

    But in general, one uses static classes in a program startup, as a utility class or as a helper class.

    using System.IO;
    using System.Web.Mvc;
    using System.Web.Optimization;
    using System.Web.Routing;
    using MVC.App_Start;
    
    namespace MVC
    {
        public class MvcApplication : System.Web.HttpApplication
        {
            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                UnityMVC5.Start();
                FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
                RouteConfig.RegisterRoutes(RouteTable.Routes);
                BundleConfig.RegisterBundles(BundleTable.Bundles);
                log4net.Config.XmlConfigurator.Configure(new FileInfo(Server.MapPath("~/Web.config")));
            }
        }
    }

    using System.Data;
    using System.Data.Common;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using Microsoft.Owin.Security;
    using Microsoft.Practices.Unity;
    using Unity.Mvc5;
    using ServiceLayer;
    using WebAPI.Controllers;
    using MVC.Models;
    
    
    namespace MVC.App_Start
    {
        public static class IocExtensions
        {
            public static void BindInRequestScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new HierarchicalLifetimeManager());
            }
    
            public static void BindInSingletonScope<T1, T2>(this IUnityContainer container) where T2 : T1
            {
                container.RegisterType<T1, T2>(new ContainerControlledLifetimeManager());
            }
        }
    
        public class UnityMVC5
        {
            public static void Start()
            {
                var container = BuildUnityContainer();
                DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            }
    
            private static IUnityContainer BuildUnityContainer()
            {
                var container = new UnityContainer();
    
                //Models
                container.BindInRequestScope<IStudentModels, StudentModels>();
                container.BindInRequestScope<IEnrollmentModels, EnrollmentModels>();
    
                //SeviceLayer
                container.BindInRequestScope<IServiceA, ServiceA>();
    
                //WebAPI controllers
                container.BindInRequestScope<IStudentControllerAPI, StudentController>();
                container.BindInRequestScope<IEnrollmentControllerAPI, EnrollmentController>();
    
                //asp.net idenity
    
                container.RegisterType<ApplicationDbContext>();
                container.RegisterType<ApplicationSignInManager>();
                container.RegisterType<ApplicationUserManager>();
                container.RegisterType<IAuthenticationManager>(
                                 new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
                container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
                            new InjectionConstructor(typeof(ApplicationDbContext)));
    
                return container;
            }
        }
    }


    Tuesday, April 2, 2019 6:11 AM
  • Ante Meridian and Cheong, please see these invitations:

    https://social.msdn.microsoft.com/Forums/vstudio/en-US/2867fff5-a57e-4413-b1b0-25208a3cfa74/adding-answerers-and-moderators-to-this-forum?forum=csharpgeneral

    Thanks!


    Ed Price, Azure Development Customer Program Manager (Blog, Small Basic, Wiki Ninjas, Wiki)

    Answer an interesting question? Create a wiki article about it!

    Wednesday, April 3, 2019 10:42 AM
    Owner