Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - use symbols from other class without qualifying with classname

Tags:

c#

I have declared a bunch of global constants in a class and now want to use these constants in other classes without always having to prefix the constants with the name of the class they have been declared in. Example:

namespace SomeName
{
   public class Constants
   {
      public const int SomeConstant = 1;
   }

   public class SomeClass
   {
      void SomeFunc ()
      {
         int i = Constants.SomeConstant;
      }
   }
}

I would like to omit Constants. from Constants.SomeConstant. Using import SomeName.Constants; didn't work. Is there a way to accomplish what I want? If yes, how would I do it?

like image 680
Razzupaltuff Avatar asked Sep 16 '25 16:09

Razzupaltuff


2 Answers

No, there's no way you can do that.

Having read your comment ("...importing a class like Math this way shortens mathematical code a bit") I can suggest this wicked code:

class MathCalculations
{
    private Func<double, double, double> min = Math.Min;
    private Func<double, double, double> max = Math.Max;
    private Func<double, double> sin = Math.Sin;
    private Func<double, double> tanh = Math.Tanh;

    void DoCalculations()
    {
        var r = min(max(sin(3), sin(5)), tanh(40));
    }
}
like image 107
Anton Gogolev Avatar answered Sep 18 '25 04:09

Anton Gogolev


Update for whoever ended up in this question thread: From the C# 6.0 on, you may do that via the using static keywords:

public class Constants
{
   public const int SomeConstant = 1;
}


using static Constants;   
public class SomeClass
{
   void SomeFunc ()
   {
      int i = SomeConstant;
   }
}
like image 45
Rzassar Avatar answered Sep 18 '25 05:09

Rzassar