I want to be able to initialize a class just like I initialize a string:
string str = "hello";
MyClass class = "hello";
I really don't know what exactly string str = "hello";
does. I assume "hello"
gets translated by the compiler into new System.String("hello");
but I'm not sure. Maybe is just not possible or maybe I'm missing something very elemental; if that's the case excuse my ignorance :). What I'm trying to make is a class that works just like a string but stores the string in a file automatically.
Ok, here's my code after reading you answers:
class StringOnFile
{
private static string Extension = ".htm";
private string _FullPath;
public bool Preserve = false;
public string FullPath
{
get
{
return _FullPath;
}
}
public static implicit operator StringOnFile(string value)
{
StringOnFile This = new StringOnFile();
int path = 0;
do{
path++;
This._FullPath = Path.GetFullPath(path.ToString() + Extension);
}
while(File.Exists(This._FullPath));
using (StreamWriter sw = File.CreateText(This._FullPath))
{
sw.Write(value);
}
return This;
}
public static implicit operator string(StringOnFile stringOnFile)
{
using (StreamReader sr = File.OpenText(stringOnFile._FullPath))
{
return sr.ReadToEnd();
}
}
~StringOnFile()
{
if(!Preserve) File.Delete(FullPath);
}
}
What do you think?
Try the following
class MyClass {
public static implicit operator MyClass(string value) {
// Custom logic here
return new MyClass();
}
}
void Example() {
MyClass v1 = "data";
}
This will get the end result you are looking for. However I would advise against this approach. There are several pitfalls with implicit conversions that you will eventually run into. Much better to just have a constructor which takes the string
Well, you can create an implicit conversion from string to your type... but I would personally rarely do so. One example of a class that does is XNamespace
from LINQ to XML. Does your class really just have a string member? If so, maybe it's suitable. Or maybe it only has a string and some other fields which can usually be defaulted... but in most cases, I wouldn't expect a conversion from string
to be appropriate.
To put it another way: should your users really think of your class in exactly the same way as a string? Is it effectively a wrapper around a string? If you could give us more details, we could give more advice.
And no, the compiler doesn't translate "hello" into new System.String("hello")
- that would just cause a recursive problem, of course, as well as breaking interning. IL has direct support for string constants, which the C# compiler uses.
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