Takeru Takeru - 3 months ago 9
C# Question

Call constructor with other class constant value

I want a constructor call to only allow a limited range of "extensions". Let's say I have these 2 classes:

public class Foo
{
public Foo(Extension ext)
{
// do something
}
}

public class Extension
{
public const string TXT = ".txt";
public const string XML = ".xml";
}


So, when another developer would want to use
Foo
he can only do so with the values from the
Extension
class like so:

Foo foo = new Foo(Extension.TXT);


But when trying to do this I get an IDE error saying:
"cannot convert from 'string' to '<ProjectName>.Extension'
.

As a "workaround" I could change my
Extension
class to something like this:

public class Extension
{
public enum File
{
TXT,
XML
}
}


and use it like this:

Foo foo = new Foo(Extension.File.TXT);


which works perfectly fine but what I do not like is that the call is one level longer (class -> enum -> element instead of class -> element).

So, the questions is is my workaround actually the only valid, correct or best practice solution?

Answer

You can use a Java style enum class

public class Extension
{
    string _Extension = null;

    private Extension(string ext)
    {
        _Extension = ext;
    }

    public static Extension TXT 
    {
        get {  return new Extension(".txt"); }
    }

    public static Extension XML
    {
        get { return new Extension(".xml"); }
    }

    public override string ToString()
    {
        return _Extension;
    }

    public override bool Equals(object obj)
    {
        var e = obj as Extension;
        if (e == null) return false;

        return e._Extension == this._Extension;
    }

    public override int GetHashCode()
    {
        return _Extension.GetHashCode();
    }
}
Comments