3

Is there a nice way to set a constant to be that of a classes namespace?

namespace ACMECompany.ACMEApp.Services
{
    public class MyService
    {
        private const string WhatWeDo = "ACMECompany.ACMEApp.Services";
        private const string WouldBeNice = typeof(MyService).Namespace;

        ...

    }
}

So that if the class if moved to another namespace we don't need to worry about these constants.

More Info The constant is only really used for logging - where it is passed to some log method. This is all legacy code so wont be changing in the short term. I am aware of runtime ways to get this information such as This Question

We're using .NET 4 but will be upgrading soon to .NET 4.5.

Community
  • 1
  • 1
Andez
  • 5,588
  • 20
  • 75
  • 116

1 Answers1

7

You're not going to set a constant variable with a non-constant value. This is understandable, isn't it?

BTW, C# has the readonly keyword, to turn any class field to work like a constant once object construction time ends. They can or can't be static:

public class MyService
{
    static MyService()
    {
         WouldBeNice = typeof(MyService).Namespace;
    }

    private static readonly string WouldBeNice;
}

or...

public class MyService
{
    private static readonly string WouldBeNice = typeof(MyService).Namespace;
}

Also, you can achieve the same behavior using read-only properties:

// Prior to C# 6...
public class MyService
{
     private static string WouldBeNice { get { return typeof(MyService).Namespace; } }
}

// Now using C# 6...
public class MyService
{
     private static string WouldBeNice => typeof(MyService).Namespace;
}

// Also using C# 6...
public class MyService
{
     // This can be even better, because this sets the namespace 
     // to the auto-generated backing class field created during compile-time
     private static string WouldBeNice { get; } = typeof(MyService).Namespace;
}
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206