user194410
user194410

Reputation: 35

C#: Struct returning variable without property

What I'd like to be able to do is have a struct return a variable without having to specify it by it's property. I'm probably phrasing this question incorrectly so I'll give an example (this fails of course). Apologies for any confusion or inconsistancies but this is what I'd like to achieve and not sure how to do this or even go about searching for it.

struct theString{  
    public string my_String;  
}

theString myString = new theString();  
string currentMethod = myString.my_String;  
string how_I_would_like_it = myString; 

Thanks in advance for any/all help.

[edit] The property string is just for the example. You can replace string with anything you'd prefer, be it int, object, webhttprequest, etc...

The problem is that when I do the string how_I_would_like_it = myString; It won't assign the my_String variable to how_I_would_like_it and the cannot implicitly convert error.

Upvotes: 2

Views: 209

Answers (2)

Mark Seemann
Mark Seemann

Reputation: 233162

You could do something like this:

public class MyString
{
    public static implicit operator string(MyString ms)
    {
        return "ploeh";
    }
}

The following unit test succeeds:

[TestMethod]
public void Test5()
{
    MyString myString = new MyString();
    string s = myString;
    Assert.AreEqual("ploeh", s);
}

In general however, I don't think this is a sign of good API design, because I prefer explicitness instead of surprises... but then again, I don't know the context of the question...

Upvotes: 4

EventHorizon
EventHorizon

Reputation: 2986

If you only want one string value returned you can try overload the struct's ToString method:

public override string ToString()
{
  return my_String;
}

Upvotes: 0

Related Questions