0

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";

?

1
  • 2
    You could create a new Perfume: public static implicit operator Perfume(string aroma) { return new Perfume { Aroma = aroma }; } Commented Oct 14, 2014 at 7:19

2 Answers 2

5

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"];
Sign up to request clarification or add additional context in comments.

1 Comment

Well, I guess it's interesting it can be done! Probably won't be useful to create a new object when you do a get instead of a set using this method, though, as you say.
0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.