M. Nasir Javaid
M. Nasir Javaid

Reputation: 5990

How can I get the name of NameSpace and Class dynamically in C#?

I have two classes, Class A and Class B. These both classes are lying in two different namespaces. I call a static method of Class B from Class A, then how can I get complete information of Class A and its namespace in called static method of Class B?

I do not want to add any code in class A But can add anything into class B.

Upvotes: 0

Views: 1361

Answers (4)

Otiel
Otiel

Reputation: 18743

You should use the GetType() method on your A object.

namespace nmspA {
    public class A{
        private void DoSomething(){
            B.Foo(this);
        }
    }
}

namespace nmspB {
    public class B {
        public static void Foo(A a){
            Debug.Write(a.GetType()); // Will write : "nmspA.A"
        }
    }
}

Upvotes: 3

L.B
L.B

Reputation: 116138

obj.GetType().FullName;

or

typeof(AClass).FullName;

Upvotes: 4

Bas Slagter
Bas Slagter

Reputation: 9929

How about you pass class A as a parameter to class B? Like:

public class A{
   public void CallB(){
      ClassB.MyMethod(this);
   }
}

public static class B {
   public static void MyMethod(A a){
       // get info about class a here.
   }
}

Of course, you can also look at the options you have with reflection if you do not want to pass the object as a parameter.

Upvotes: 2

Related Questions