We all know this thing
bool.Parse(Session["foo"].ToString())
How do implement the same PARSE method for some custom class?
So if I have
class MyClass
{
}
It would be possible to do like
MyClass.Parse(Session["foo"])
All you need to do is write a static method called Parse() for your class that takes the String and creates an Instance of MyClass with it.
public class MyClass
{
public static MyClass Parse(string input)
{
if(String.IsNullOrWhiteSpace(input)) throw new ArgumentException(input);
var instance = new MyClass();
// Parse the string and populate the MyClass instance
return instance;
}
}
Absolutely - you would need to write a moderate amount of code to implement it, but you can certainly do it manually if you must:
public class MyClass {
public string First {get; private set;}
public string Last {get; private set;}
public MyClass(string first, string last) {
First = first;
Last = last;
}
public static bool Parse(string s, out MyClass res) {
res = null;
if (s == null) return false;
var tokens = s.Split(new[] {';'});
if (tokens.Length != 2) return false;
res = new MyClass(tokens[0], tokens[1]);
return true;
}
}
This version takes an output argument and returns bool; you can easily modify it to throw an exception and return MyClass "the factory method style".
Parse()method?MyClassin theSession?