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