Search code examples
c#wpfcoding-style

Use static function into the class to return it initialize


I just have a question about this example. Use Static function into my class to create the object with the correct type. Is it a coding standard or just weird ?

public partial class Example
{
    public enum enumType
    {
        typeA,
        typeB
    }

    private string type;

    public Example(enumType type)
    {
        if ( type == enumType.typeA)
        {
            this.type = enumType.typeA.ToString();
        }
        else
        {
            this.type = enumType.typeB.ToString();
        }
    }

    public static Example CreateAsTypeA()
    {
        return new Example(enumType.typeA);
    }
    public static Example CreateAsTypeB()
    {
        return new Example(enumType.typeB);
    }
}

Solution

  • Yes, your method should be static.

    Because they are essentially constructing a variation of the class, there is no need to store anything about the instance of the object. You method's are more or less constructors, not so much properties. That said, you may want to look into the concept of a static constructor. Here is a link : https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constructors