Parse method for the custom class C#

c#

Solution

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

Problem

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"]) ```

Original source