get the namespace in a variable in c #

1

Currently I develop an app in C # (business layer) where I need to get in a variable of type string, the namespace of the function that is running.

This I get in the following way;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test28
{
    class Program
    {
        static void Main(string[] args)
        {
            string NameSpace = System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.Namespace;
        }
    }

This works well, when executed within a project of type aplicacon console .Net Framework

It also works if I create a separate class in the same project, and I use the same method to get the namespace.

The problem is when I want to get the namespace in a project of the .Net Framework class library type.

If the code is executed there, I get the following error:

**

  

Reference to object not established as an instance of an object.

**

Does anyone know what instruction should be used to get the namespace name in a library of .Net Framework classes?

    
asked by Luis Gabriel Fabres 05.03.2018 в 23:33
source

1 answer

2

I leave you 3 options to get the namespace of a class. You can generalize it to this code by placing it in a superclass

A simple example

namespace Starwars.Core.Force 
{
  public class LightSide
  {
    private const string StringToRemove = ".LightSide";

    public string GetNamespace1()
    {
        return this.ToString().Replace(StringToRemove, string.Empty);
    }

    public string GetNamespace2()
    {
        var type = typeof(LightSide);
        return type.Namespace;
    }

    public string GetNamespace3()
    {
        var type = this.GetType();
        return type.Namespace;
    }
  }
}
    
answered by 06.03.2018 / 00:07
source