Is this possible!!?!?!?!?
I'm trying to make a set of classes that model a number of different types of things. Properties of these things change over time, and I want my code to be easy to maintain, so I want to do something like the following:
public class Cat
{
public string CatName { get; set; }
public Cat()
{
this.CatName = MAGICSTUFF.GetInstanceName(this);
}
}
Somewhere else, when I want to get at those cats, I want to be able to say:
[TestMethod]
public void test_awesome_cats()
{
Cat Tiger = new Cat();
Assert.IsTrue(Tiger.CatName.Equals("Tiger"));
}
So, I'm trying to map my naming convention into object properties. The part I can't figure out is the MAGICSTUFF.GetInstanceName. Is that a thing?
I suspect this is impossible, so if that's the case hopefully somebody can give me some other ideas on clever ways to use convention for this type of scenario. I've been thinking of using attributes for the Cat class for a while, but I like this was a lot better if its possible.
It's not possible to do that kind of reflection. Variable names could be erased by the compiler depending on debugging options and scope. The name of a variable is an alias of its "address" so can not be reversed (at least in Java and C# AFAIK).
An object can be pointed from nay variables, so the variable name is irrelevant and the object don't know this kind of stuff:
Cat tiger = new Cat();
Cat tiger2 = tiger;
Variable tiger2
points to the Cat
"tiger", so 2 variable points same object with different names.
Use class properties passed in the constructor.
The normal way of doing this is to store the 'name' as a variable in the instance, for ex:
// Initialize this like: var cat = new Cat("Tiger");
class Cat {
public String Name { get; private set; }
public Cat(String name)
{
Name = name;
}
}
And then if you need to get tigers in more than one place, make it into a method that explicitly returns Tigers:
// This can go into a class of cat-creating static methods. Or maybe in the Cat class itself.
public static Cat GiveMeATiger() {
return new Cat("Tiger");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With