Kyle Michiels
Kyle Michiels

Reputation: 25

C# Get class declaration name

Is it possible to get the declaration name of a class (dynamically) and pass it as a parameter in the constructor to set the name variable in the class itself?

Example:

public class Foo
{
    public string name;
    public Foo()
    {
        name = GetClassName();
    }
}

public class SomeOtherClass
{
    Foo className = new Foo();
    Console.WriteLine(foo.name);
}

As result I would expect it to write: "className".

Upvotes: 0

Views: 958

Answers (2)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37115

That sounds like a weird requirement. A variable is nothing but a reference to an object. The name of that reference has by no means anything to do with what this variable reference. Thus the actual referenced object doesn´t know anything about its references. In fact you may have even multiple references to the same Foo-instance. So how should the instance know to which variable you refer to? So what should happen in the following example:

var f = new Foo();
var b = f;

Now you have two references to the same instance of Foo. The instance can´t know which of hose is the right, unless you provide that information to it by using a parameter (e.g. to your constructor). The thing gets even worse if you have a factory creating your Foo-instance:

void CreateFoo()
{
    return new Foo();
}
// ...
var f = CreateFoo();

Now you have a further indirection, the constructor of Foo can surely not bubble though all layers in your call-stack until it reaches some assignement where it may get the actual name. In fact it´s possible that you don´t even assign your instance to anything - although this is merely a good idea:

CreateFoo();  // create an instance and throw it away

Anyway if you want to set a member of an instance to some value, you should provide that value to the instance. The answer by Patrick shows you how to do so.

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157108

No. That is not possible. There is no way to pass in a variable name without using a parameter.

This is the closest you can get:

Foo className = new Foo(nameof(className));

Upvotes: 3

Related Questions