Tyress
Tyress

Reputation: 3653

Getting, Setting values using Class name

I am hoping I don't get a flood of downvotes for this question, but I was wondering if there is a way to use the actual class name, without calling properties, to get and set values. So for example, if I were to have:

class Perfume
{
  private string _aroma;
  public string Aroma
  {
   set
   {
    _aroma = value;
   }
  }
}

Would there be a way to do:

Perfume perfume = new Perfume();
perfume = "Aroma"; // which will set _aroma to "Aroma";

?

Upvotes: 0

Views: 70

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460268

One way (that i wouldn't use) is to provide an implicit conversion from string to Perfume:

public static implicit operator Perfume(string aroma)
{
    return new Perfume { Aroma = aroma };
}

Then this works:

Perfume perfume = new Perfume();
perfume = "aroma";

But it needs to create a new object which is rarely desired since it deletes all other properties and also makes the code less readable (the first line is pointless since it creates a throwaway-Perfume).

As an aside, normally an Aroma would also be a class with properties instead of a string. Another way is to provide an enum of available aromas. That increases readability and makes the code more robust.

But maybe you are actually looking for a way to find your perfumes via aroma-name. Then a Dictionary<string, Perfume> (or Dictionary<Aroma, Perfume>, where Aroma is the enum) was more appropriate:

Dictionary<string, Perfume> allAromas = new Dictionary<string, Perfume>();
allAromas.Add("Musky", new Perfume{Aroma="Musky"});
allAromas.Add("Putrid", new Perfume{Aroma="Putrid"});
allAromas.Add("Pungent", new Perfume{Aroma="Pungent"});
allAromas.Add("Camphoraceous", new Perfume{Aroma="Camphoraceous"});
allAromas.Add("Pepperminty", new Perfume{Aroma="Pepperminty"});

Now you can access a perfume later very fast via aroma-name:

Perfume muskyPerfume = allAromas["Musky"];

Upvotes: 5

Silas Reinagel
Silas Reinagel

Reputation: 4223

There is the standard way of setting details.

Perfume perform = new Perfume(){ Aroma = "aroma" };

Or via constructor injection if you add a new constructor, which is fairly standard.

Perfume perfume = new Perfume("Aroma");

public class Perfume
{
    public string Aroma { get; set; }

    public Perfume(string aroma)
    {
        Aroma = aroma;
    }
}

Upvotes: 0

Related Questions