0

I always knew that I have to use static methods but I wonder why? As you can see below I have to make "MigrateDatabase" Static

using System;

namespace OdeToFood
{
    public class Program
    {
        public static void Main(string[] args)
        {
            MigrateDatabase();
        }

        private static void MigrateDatabase()
        {
          //.....
        }


    }
}

Azizamari
  • 56
  • 1
  • 5
  • 4
    In this case it's because you can't call non static functions from static functions in this specific case. – IndieGameDev Dec 09 '20 at 15:11
  • You have to make it static _for this code_ but you don't have to make it static if you write the code differently. – Jamiec Dec 09 '20 at 15:12
  • `new Program().MigrateDatabase()` is my go to in such cases, since typing `static` every time is a pain. – Jeroen Mostert Dec 09 '20 at 15:12
  • @MathewHD: not really true: you can call non-static functions from static functions, if you have a reference to the object containing the method. – Bestter Dec 09 '20 at 15:13
  • Also: https://stackoverflow.com/questions/33705976/when-should-i-use-static-methods/33706003 –  Dec 09 '20 at 15:14
  • @MathewHD That's just not true. You can absolutely call instance methods from static methods. You just need to provide an instance when calling them method. It's *super* common to call instance methods from static methods. In fact I'd guess a large majority of static methods call an instance method. – Servy Dec 09 '20 at 15:16
  • I make all functions static that I want to call across my froms to make them independent from any instance variables. – TaW Dec 09 '20 at 16:18
  • I guess the duplicate is fne here, but it should be noted that it is not for c# but java. – TaW Dec 09 '20 at 16:19

1 Answers1

0

Let's just be clear, the only reason MigrateDatabase has to be static in this case is because you're calling it from a static method (Main). If instead MigrateDatabase was an instance method on a class, you could instantiate that class and call it

using System;

namespace OdeToFood
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var migration = new Migration();
            migration.MigrateDatabase();
        }   
    }

    public class Migration
    {
        private void MigrateDatabase()
        {
          //.....
        }
    }
}

You could also put it as a instance method on Program if you're instantiating an instance of that class

using System;

namespace OdeToFood
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var program = new Program();
            program.MigrateDatabase();
        }

        private void MigrateDatabase()
        {
          //.....
        }


    }
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 2
    People: I'm happy for my answers to be edited with corrections, but please don't wholesale change it! – Jamiec Dec 09 '20 at 15:33